Classic Sorting Algorithm and Sorting Algorithm
Classic sorting algorithm-Quick sorting
Principle: The data to be sorted is divided into two independent parts by one scan. All the data in one part is smaller than all the data in the other part, then, sort the two data parts by using this method. The entire sorting process can be recursive to convert the entire data into an ordered sequence.
For example
For example, unordered array [6 2 4 1 5 9]
A)First, obtain the first item [6,
Use [6] to compare with the remaining items in sequence,
If it is smaller than [6], put the front edge of [6], and 2, 4, 1, and 5 are smaller than [6]. Therefore, put all the data in the front edge of [6 ].
If it is bigger than [6], put it behind [6], and 9 is bigger than [6]. Put it behind [6], and then give it a drink after listing it, if you are a little bit older than me, you can take action! Domineering ~
After a row is completed, it becomes the following:
Sorting top 6 2 4 1 5 9
2 4 1 5 6 9 after sorting
B)To continue the quick sorting for the first half pull [2 4 1 5]
Repeat Step:
Sorting Top 2 4 1 5
1 2 4 5 after sorting
The first half is sorted, and the total sorting is also completed:
Before sorting: [6 2 4 1 5 9]
After sorting: [1 2 4 5 6 9]
Sorting ends
The following code is for reference only.
static int partition(int[] unsorted, int low, int high) { int pivot = unsorted[low]; while (low < high) { while (low < high && unsorted[high] > pivot) high--; unsorted[low] = unsorted[high]; while (low < high && unsorted[low] <= pivot) low++; unsorted[high] = unsorted[low]; } unsorted[low] = pivot; return low; } static void quick_sort(int[] unsorted, int low, int high) { int loc = 0; if (low < high) { loc = partition(unsorted, low, high); quick_sort(unsorted, low, loc - 1); quick_sort(unsorted, loc + 1, high); } } static void Main(string[] args) { int[] x = { 6, 2, 4, 1, 5, 9 }; quick_sort(x, 0, x.Length - 1); foreach (var item in x) { Console.WriteLine(item + ","); } Console.ReadLine(); }