C++ 迴圈排序程式?


迴圈排序是一種就地、不穩定的排序演算法,一種比較排序,在原始陣列的總寫入次數方面理論上最優,這與其他任何就地排序演算法不同。其思想基礎是待排序的排列可以分解成迴圈,各個迴圈輪轉即可得到排序結果。

與幾乎所有其他排序不同,只需將項寫入陣列的其他位置來將其移出操作路徑。每個值要麼被寫入零次(如果其已處於正確位置),要麼被寫入一次(到其正確位置)。這與完成就地排序所需的最少覆蓋次數相一致。

當對大型資料集進行寫入非常昂貴(例如,對快閃記憶體等 EEPROM 進行寫入會縮短記憶體使用壽命)時,最小化寫入次數十分有用。

Input: a[]={7,4,3,5,2,1,6}
Output: 1 2 3 4 5 6 7

說明

arr[] = {10, 5, 2, 3}
index = 0 1 2 3
cycle_start = 0
item = 10 = arr[0]
Find position where we put the item,
pos = cycle_start
while (arr[i] < item)
pos++;
We put 10 at arr[3] and change item to
old value of arr[3].
arr[] = {10, 5, 2, 10}
item = 3
Again rotate rest cycle that start with index '0'
Find position where we put the item = 3
we swap item with element at arr[1] now
arr[] = {10, 3, 2, 10}
item = 5
Again rotate rest cycle that start with index '0' and item = 5
we swap item with element at arr[2].
arr[] = {10, 3, 5, 10 }
item = 2
Again rotate rest cycle that start with index '0' and item = 2
arr[] = {2, 3, 5, 10}
Above is one iteration for cycle_stat = 0.
Repeat above steps for cycle_start = 1, 2, ..n-2

示例

#include<iostream>
using namespace std;
void cycleSort(int a[], int n) {
   int writes = 0;
   for (int c_start = 0; c_start <= n - 2; c_start++) {
      int item = a[c_start];
      int pos = c_start;
      for (int i = c_start + 1; i < n; i++)
         if (a[i] < item)
            pos++;
      if (pos == c_start)
         continue;
      while (item == a[pos])
         pos += 1;
      if (pos != c_start) {
            swap(item, a[pos]);
            writes++;
      }
      while (pos != c_start) {
         pos = c_start;
         for (int i = c_start + 1; i < n; i++)
            if (a[i] < item)
         pos += 1;
         while (item == a[pos])
            pos += 1;
         if (item != a[pos]) {
            swap(item, a[pos]);
            writes++;
         }
      }
   }
}
int main() {
   int a[] ={7,4,3,5,2,1,6};
   int n = 7;
   cycleSort(a, n);
   for (int i = 0; i < n; i++)
      cout << a[i] << " ";
   return 0;
}

更新於: 20-Aug-2019

392 次瀏覽

開啟你的職業生涯

透過完成課程取得認證

開始學習
廣告
© . All rights reserved.