Đặt mảng không được sắp xếp trước.
int[] list = {87, 45, 56, 22, 84, 65}; Bây giờ, hãy sử dụng vòng lặp for lồng nhau để sắp xếp danh sách, danh sách được chuyển cho một hàm.
for(int i=0; i< arr.Length; i++) {
for(int j=i+1; j<arr.Length; j++) {
if(arr[i]>=arr[j]) {
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
Console.Write(arr[i] + " ");
} Sau đây là mã hoàn chỉnh để sắp xếp mảng một chiều theo thứ tự tăng dần bằng phương pháp không tĩnh.
Ví dụ
using System;
namespace Demo {
public class MyApplication {
public static void Main(string[] args) {
int[] list = {87, 45, 56, 22, 84, 65};
Console.WriteLine("Original Unsorted List");
foreach (int i in list) {
Console.Write(i + " ");
}
MyApplication m = new MyApplication();
m.sortFunc(list);
}
public void sortFunc(int[] arr) {
int temp = 0;
Console.WriteLine("\nSorted List");
for(int i=0; i< arr.Length; i++) {
for(int j=i+1; j<arr.Length; j++) {
if(arr[i]>=arr[j]) {
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
Console.Write(arr[i] + " ");
}
}
}
} Đầu ra
Original Unsorted List 87 45 56 22 84 65 Sorted List 22 45 56 65 84 87