迴圈排序
迴圈排序是一種原地排序演算法。它也是一種基於比較的排序,並且比任何其他原地排序技術都高效。它找到執行排序任務所需的最小記憶體寫入數量。
迴圈排序技術的複雜性
- 時間複雜度: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