ในเทคนิคการเรียงลำดับการเลือก รายการจะแบ่งออกเป็นสองส่วน ในส่วนหนึ่งองค์ประกอบทั้งหมดจะถูกจัดเรียงและในส่วนอื่นองค์ประกอบจะไม่ถูกจัดเรียง ตอนแรกเราใช้ข้อมูลสูงสุดหรือต่ำสุดจากอาร์เรย์ หลังจากได้รับข้อมูล (พูดขั้นต่ำ) เราวางไว้ที่จุดเริ่มต้นของรายการโดยแทนที่ข้อมูลของตำแหน่งแรกด้วยข้อมูลขั้นต่ำ หลังจากดำเนินการอาร์เรย์มีขนาดเล็กลง ดังนั้นเทคนิคการเรียงลำดับนี้จึงเสร็จสิ้น
ความซับซ้อนของเทคนิคการเรียงลำดับการเลือก
-
ความซับซ้อนของเวลา:O(n 2 )
-
ความซับซ้อนของอวกาศ:O(1)
Input − The unsorted list: 5 9 7 23 78 20 Output − Array after Sorting: 5 7 9 20 23 78
อัลกอริทึม
selectionSort(อาร์เรย์, ขนาด)
ป้อนข้อมูล :อาร์เรย์ของข้อมูลและจำนวนทั้งหมดในอาร์เรย์
ผลผลิต :The sorted Array
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