Sắp xếp lựa chọn trong chương trình Java với ví dụ

Anonim

Lựa chọn Sắp xếp hoạt động như thế nào?

Lựa chọn Sắp xếp thực hiện một thuật toán sắp xếp đơn giản như sau:

  • Thuật toán liên tục tìm kiếm phần tử thấp nhất.
  • Hoán đổi phần tử hiện tại với phần tử có giá trị thấp nhất
  • Với mỗi lần lặp / vượt qua sắp xếp lựa chọn, các phần tử được hoán đổi vị trí.

Chương trình Java để triển khai Sắp xếp Lựa chọn

gói com.guru99;lớp công cộng SelectionSortAlgo {public static void main (String a []){int [] myArray = {860,8,200,9};System.out.println ("------ Trước khi Sắp xếp Lựa chọn -----");printArray (myArray);lựa chọn (myArray); // sắp xếp mảng sử dụng sắp xếp lựa chọnSystem.out.println ("----- Sau khi Sắp xếp Lựa chọn -----");printArray (myArray);}public static void selection (int [] array){for (int i = 0; i 

Đầu ra:

------Before Selection Sort-----860 8 200 9Sort Pass Number 1Comparing 860 and 8860 is greater than 8Comparing 8 and 200Comparing 8 and 9Swapping Elements: New Array After Swap8 860 200 9Sort Pass Number 2Comparing 860 and 200860 is greater than 200Comparing 200 and 9200 is greater than 9Swapping Elements: New Array After Swap8 9 200 860Sort Pass Number 3Comparing 200 and 860Swapping Elements: New Array After Swap8 9 200 860-----After Selection Sort-----8 9 200 860