C++ 程式設計實現希爾排序


希爾排序技術是基於插入排序的。在插入排序中,有時我們需要移動較大的塊,才能將項插入正確位置。使用希爾排序,我們可以避免大量移動。排序使用特定的間隔來進行。每次通過後,間隔變小,形成較小的間隔。

希爾排序技術的複雜度

  • 時間複雜度:最佳情況為 O(n log n),對於其他情況,這取決於間隙序列。

  • 空間複雜度:O(1)

Input − The unsorted list: 23 56 97 21 35 689 854 12 47 66
Output − Array after Sorting: 12 21 23 35 47 56 66 97 689 854

演算法

shellSort(array, size)

輸入:一個數據陣列,以及陣列中的總數

輸出:已排序的陣列

Begin
   for gap := size / 2, when gap > 0 and gap is updated with gap / 2 do
      for j:= gap to size– 1 do
         for k := j-gap to 0, decrease by gap value do
            if array[k+gap] >= array[k]
               break
            else
               swap array[k + gap] with array[k]
         done
      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 shellSort(int *arr, int n) {
   int gap, j, k;
   for(gap = n/2; gap > 0; gap = gap / 2) {        //initially gap = n/2,
      decreasing by gap /2
      for(j = gap; j<n; j++) {
         for(k = j-gap; k>=0; k -= gap) {
            if(arr[k+gap] >= arr[k])
               break;
            else
               swapping(arr[k+gap], arr[k]);
         }
      }
   }
}
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);
   shellSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}

輸出

Enter the number of elements: 10
Enter elements:
23 56 97 21 35 689 854 12 47 66
Array before Sorting: 23 56 97 21 35 689 854 12 47 66
Array after Sorting: 12 21 23 35 47 56 66 97 689 854

更新日期:2019 年 7 月 30 日

2K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.