C++ 程式實現選擇排序


在選擇排序技術中,將列表分為兩部分。一部分中的所有元素都已排序,另一部分中的專案未排序。首先,我們從陣列中獲取最大值或最小值。在獲取資料(如最小值)後,我們透過將第一個位置的資料替換為最小資料,將其放入列表的開頭。執行後,陣列將變小。因此,這種排序技術得以完成。

選擇排序技術的時間複雜度

  • 時間複雜度:O(n2)

  • 空間複雜度:O(1)

Input − The unsorted list: 5 9 7 23 78 20
Output − Array after Sorting: 5 7 9 20 23 78

演算法

selectionSort(array, size)

輸入:一個數據陣列和陣列中的總數

輸出:已排序的陣列

Begin
   for i := 0 to size-2 do //find minimum from ith location to size
      iMin := i;
      for j:= i+1 to size – 1 do
         if array[j] < array[iMin] then
            iMin := j
      done
      swap array[i] with array[iMin].
   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 selectionSort(int *array, int size) {
   int i, j, imin;
   for(i = 0; i<size-1; i++) {
      imin = i;   //get index of minimum data
      for(j = i+1; j<size; j++)
         if(array[j] < array[imin])
            imin = j;
         //placing in correct position
         swap(array[i], array[imin]);
   }
}
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);
   selectionSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}

輸出

Enter the number of elements: 6
Enter elements:
5 9 7 23 78 20
Array before Sorting: 5 9 7 23 78 20
Array after Sorting: 5 7 9 20 23 78

更新於: 30-Jul-2019

20K+ 瀏覽次數

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.