Chương trình Java để triển khai thuật toán sắp xếp bong bóng

Trong ví dụ này, chúng ta sẽ học cách thực thi thuật toán sắp xếp bong bóng trong Java.

Để hiểu ví dụ này, bạn nên có kiến ​​thức về các chủ đề lập trình Java sau:

  • Phương thức Java
  • Java cho Vòng lặp
  • Mảng Java

Ví dụ: Chương trình Java để triển khai thuật toán sắp xếp bong bóng

 // import the Class import java.util.Arrays; import java.util.Scanner; class Main ( // create an object of scanner // to take input from the user Scanner input = new Scanner(System.in); // method to perform bubble sort void bubbleSort(int array()) ( int size = array.length; // for ascending or descending sort System.out.println("Choose Sorting Order:"); System.out.println("1 for Ascending 2 for Descending"); int sortOrder = input.nextInt(); // run loops two times // first loop access each element of the array for (int i = 0; i < size - 1; i++) // second loop performs the comparison in each iteration for (int j = 0; j  array(j + 1)) ( // swap if left element is greater than right int temp = array(j); array(j) = array(j + 1); array(j + 1) = temp; ) ) // sort the array in descending order else ( // compares the adjacent element if (array(j) < array(j + 1)) ( // swap if left element is smaller than right int temp = array(j); array(j) = array(j + 1); array(j + 1) = temp; ) ) ) // driver code public static void main(String args()) ( // create an array int() data = ( -2, 45, 0, 11, -9 ); // create an object of Main class Main bs = new Main(); // call the method bubbleSort using object bs // pass the array as the method argument bs.bubbleSort(data); System.out.println("Sorted Array in Ascending Order:"); // call toString() of Arrays class // to convert data into the string System.out.println(Arrays.toString(data)); ) ) 

Đầu ra 1

 Chọn Thứ tự sắp xếp: 1 cho Tăng dần 2 cho Giảm dần 1 Mảng đã sắp xếp: (-9, -2, 0, 11, 45)

Trong trường hợp này, chúng tôi đã nhập 1 làm đầu vào. Do đó, chương trình sắp xếp mảng theo thứ tự tăng dần.

Đầu ra 2

 Chọn Thứ tự sắp xếp: 1 cho Tăng dần 2 cho Giảm dần 2 Mảng đã sắp xếp: (45, 11, 0, -2, -9)

Trong trường hợp này, chúng tôi đã nhập 2 làm đầu vào. Do đó, chương trình sắp xếp mảng theo thứ tự giảm dần.

Nếu bạn muốn tìm hiểu thêm về thuật toán sắp xếp bong bóng, hãy truy cập Thuật toán sắp xếp bong bóng.

Lưu ý : Chúng tôi đã sử dụng Lớp máy quét Java để lấy đầu vào từ người dùng.

thú vị bài viết...