循环排序
循环排序是一种原地排序算法。它也是一种基于比较的排序,并且比任何其他原地排序技术都高效。它找到执行排序任务所需的最小内存写入数量。
循环排序技术的复杂性
- 时间复杂度: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 << "Enter elements:" << 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 Enter elements: 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
广告
数据结构
网络
关系型 DBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP