ที่นี่เราจะเห็นอัลกอริธึมการเรียงลำดับอื่นที่เรียกว่า Bogo Sort การเรียงลำดับนี้เรียกอีกอย่างว่าการเรียงลำดับการเรียงสับเปลี่ยน, การเรียงลำดับโง่, การเรียงลำดับช้า ฯลฯ อัลกอริธึมการเรียงลำดับนี้เป็นเทคนิคการเรียงลำดับที่ไม่มีประสิทธิภาพโดยเฉพาะ สิ่งนี้อยู่ภายใต้กระบวนทัศน์การสร้างและทดสอบ มันสร้างการเรียงสับเปลี่ยนซ้ำ ๆ จนกว่าจะมีการเรียงลำดับ แนวความคิดตรงไปตรงมามาก จนกว่ารายการจะถูกจัดเรียง เพียงแค่สับเปลี่ยนองค์ประกอบ
อัลกอริทึม
bogoSort(อาร์เรย์ n)
Begin while the arr is not sorted, do shuffle arr done End
ตัวอย่าง
#include<iostream>
#include<cstdlib>
using namespace std;
bool isSorted(int arr[], int n) { //check whether the list is sorted
or not
while (--n > 1)
if (arr[n] < arr[n - 1])
return false;
return true;
}
void shuffle(int arr[], int n) {
for (int i = 0; i < n; i++)
swap(arr[i], arr[rand() % n]);
}
void bogoSort(int arr[], int n){
while (!isSorted(arr, n))
shuffle(arr, n);
}
main() {
int data[] = {54, 74, 98, 5, 98, 32, 20, 13, 35, 40};
int n = sizeof(data)/sizeof(data[0]);
cout << "Sorted Sequence ";
bogoSort(data, n);
for(int i = 0; i <n;i++){
cout << data[i] << " ";
}
} ผลลัพธ์
Sorted Sequence 5 13 20 32 35 40 54 74 98 98