循环排序是一种就地排序算法。它也是基于比较的排序,对于任何其他就地排序技术而言都是有效的。它找到执行排序任务所需的最小内存写入数。
时间复杂度:O(n ^ 2)
空间复杂度:O(1)
Input: A list of unsorted data: 23 63 98 74 20 14 36 45 99 78 Output: Array before Sorting: 23 63 98 74 20 14 36 45 99 78 Array after Sorting: 14 20 23 36 45 63 74 78 98 99
cycleSort(array, size)
输入-数据数组,以及数组中的总数
输出- 排序的数组
Begin for start := 0 to n – 2 do key := array[start] location := start for i := start + 1 to n-1 do if array[i] < key then location:=location +1 done if location = start then ignore lower part, go for next iteration while key = array[location] do location := location +1 done if location ≠ start then swap array[location] with key while location ≠ start do location := start for i := start + 1 to n-1 do if array[i] < key then location:=location +1 done while key = array[location] location := location +1 if key ≠ array[location] swap array[location] and key done done End
#include<iostream> using namespace std; void swapping(int &a, int &b) { //swap the content of a and b int temp; temp = a; a = b; b = temp; } void display(int *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void cycleSort(int *array, int n) { for(int start = 0; start<n-1; start++) { //put array element in the correct place int key = array[start]; int location = start; for(int i = start+1; i<n; i++) { //count smaller element in the right side of key if(array[i] < key) location++; } if(location == start) //when it is in correct place go for next iteration continue; while(key == array[location]) //if same data is found increase location location++; if(location != start) swapping(array[location], key); while(location != start) { location = start; for(int i = start+1; i<n; i++) { //location to put element if(array[i] < key) location++; } while(key == array[location]) //if same data is found increase location location++; if(key != array[location]) swapping(key, array[location]); } } } int main() { int n; cout << "Enter the number of elements: "; cin >> n; int arr[n]; //create an array with given number of elements cout << "输入元素:" << endl; for(int i = 0; i<n; i++) { cin >> arr[i]; } cout << "Array before Sorting: "; display(arr, n); cycleSort(arr, n); cout << "Array after Sorting: "; display(arr, n); }
输出结果
Enter the number of elements: 10 输入元素: 23 63 98 74 20 14 36 45 99 78 Array before Sorting: 23 63 98 74 20 14 36 45 99 78 Array after Sorting: 14 20 23 36 45 63 74 78 98 99