C++ 程式執行笨鳥排序


笨鳥排序用於對給定資料進行排序。它是一種遞迴排序演算法。笨鳥排序將陣列分成兩個重疊的部分,每個部分佔 2/3,並透過先對 I 進行排序、然後對 II 進行排序、最後再對 I 部分進行排序這三個步驟對陣列進行排序。該演算法的最壞情況時間複雜度為 O(n^2.7095)。

演算法

Begin
   Take input of data.
   Call StoogeSort() function with ‘a’ the array of data and ‘n’ the number of values, in the argument list.
   Implement Sorting using recursive approach.
   Divide the array into first 2/3 element as part I and last 2/3 as part II.
   Then send the first, second and again first part into StoogeSort().
   If the length is not further breakable then swap element at the start and end if a[end] < a[start].
   Return to main and display the result.
End.

示例程式碼

#include<iostream>
using namespace std;
void StoogeSort(int a[],int start, int end) {
   int temp;
   if(end-start+1 > 2) {
      temp = (end-start+1)/3;
      StoogeSort(a, start, end-temp);
      StoogeSort(a, start+temp, end);
      StoogeSort(a, start, end-temp);
   }
   if(a[end] < a[start]) {
      temp = a[start];
      a[start] = a[end];
      a[end] = temp;
    }
}
int main() {
   int m, i;
   cout<<"\nEnter the number of data element to be sorted: ";
   cin>>m;
   int arr[m];
   for(i = 0; i < m; i++) {
      cout<<"Enter element "<<i+1<<": ";
      cin>>arr[i];
   }
   StoogeSort(arr, 0, m-1);
   cout<<"\nSorted Data ";
   for (i = 0; i < m; i++)
      cout<<"->"<<arr[i];
   return 0;
}

輸出

Enter the number of data element to be sorted: 4
Enter element 1: 6
Enter element 2: 7
Enter element 3: 3
Enter element 4: 2
Sorted Data ->2->3->6->7

更新於:2019 年 7 月 30 日

257 人次瀏覽

啟動你的職業生涯

完成課程以獲取認證

立即開始
廣告
© . All rights reserved.