Chào mọi người code bài của em đây nhưng mà không hiểu sao cái hàm tìm kiếm và sắp xếp của em nó không hoạt động vậy ạ.Hàm sắp xếp thì nó không tin ra được các phần tử đã sắp xếp còn hàm tìm kiếm thì nó không hiển thị đúng vị trì cần tìm kiếm ạ.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Bai3Chuong3
{
class Mang1Chieu
{
private int n;
private int[] a;
public Mang1Chieu(int n)
{
this.n = n;
a = new int[n];
}
public void nhap(int n)
{
for (int i = 0; i < n; i++)
{
Console.Write("a[" + i + "]=");
a[i] = int.Parse(Console.ReadLine());
}
}
public void xuat(int n)
{
for (int i = 0; i < n; i++)
{
Console.Write(a[i] + " ");
}
Console.WriteLine();
}
public void sapxep(int thutu)
{
if (thutu == 0)
{
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[j] < a[i])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
Console.Write("\nIn cac phan tu mang theo thu tu tang dan:\n");
for (int i = 0; i < n; i++)
{
Console.Write("{0} ", a[i]);
}
}
if (thutu == 1)
{
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[j] > a[i])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
Console.Write("\nIn cac phan tu mang theo thu tu giam dan:\n");
for (int i = 0; i < n; i++)
{
Console.Write("{0} "+ a[i]);
}
}
}
public int timkiem(int m)
{
int vt = 0;
int dem = 0;
for (int i = 0; i < n; i++)
{
if (a[i] == m)
{
vt = i;
dem++;
}
}
if (dem == 0) { return -1; }
else return vt;
}
static void Main(string[] args)
{
int n, thutu, m;
Console.Write("Nhap so phan tu : ");
n = int.Parse(Console.ReadLine());
Mang1Chieu b = new Mang1Chieu(n);
Console.WriteLine("Nhap phan tu");
b.nhap(n);
Console.WriteLine("Hien thi mang");
b.xuat(n);
Console.Write("Nhap gia tri can tim kiem : ");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Vi tri can tim kiem ", b.timkiem(m));
Console.ReadKey();
}
}
}
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?