bubble:
The basic idea of bubbling is that for unordered data, the nested loop compares the size, and the time complexity is O(n^2);
package algorithm;
/**
* bubble sort,
*/
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {7, 9, 2, 6, 0, 3, 8};
for (int i = 0; i < arr.length; i++) {//The outer loop controls the number of sorting passes
for (int j = i+1; j < arr.length; j++) {//The inner loop controls each How many times to sort
if (arr[i] > arr[j]) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
for(int k :arr ){
System.out.print(k+" ");
}
System.out.println("--");
}
for(int i :arr){
System.out.println(i);
}
}
}
Selection sort:
Compared with bubble sort, the number of necessary exchanges is reduced from O(n^2) to O(n); in selection sort, instead of only comparing two adjacent data, it is necessary to record a specified data
public class SelectSort {
public static void selectionSort(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int k = i;
// find the subscript of the minimum value
for (int j = i + 1; j < n; j++) {
if (a[j] < a[k]) {
k = j;
}
}
// put minimum value at end of sorted sequence
if (k > i ) {
int tmp = a[i];
a[i] = a[k];
a[k] = tmp;
}
for (int g : a){
System.out.print(g+ " ");}
System. out.println("------------");
}
}
public static void main(String[] args) {
int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 };
selectionSort(b);
for (int i : b)
System.out.print(i + " ");
}
}