1. Bubble Sorting
1) Principle Description: repeat the series to be sorted, compare two elements at a time, and exchange them if their order is wrong. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted.
2) code implementation:
package com.test.sort;public class BubbleSort{ public static void sort(int[] data) { for (int i = 0; i < data.length; i++) { for (int j = data.length - 1; j > i; j--) { if (data[j] < data[j - 1]) { swap(data, j, j - 1); } } } } private static void swap(int[] data, int a, int b) { int temp = data[a]; data[a] = data[b]; data[b] = temp; } public static void main(String[] args) { int[] data = new int[] { 3, 5, 55, 34, 67, 3, 78, 3423, 675, 4567 }; sort(data); System.out.print("result is: {"); for (int temp : data) { System.out.print(temp + " "); } System.out.print("}"); }}
2. Simple selection and sorting
1) Principle Description: the basic idea of simple sorting is very simple, that is, the first line is to find the element with the smallest keyword from n elements and exchange with the first element; the second, in the n-1 elements starting from the second element, the element with the smallest keyword is then selected for exchange with the second element. In this way, the k-th Column, then, from the n-k + 1 element starting with the k element, the element with the smallest keyword is selected to exchange with the k element until the entire sequence is ordered by the keyword.
2) code implementation:
package com.test.sort;public class SelectSort{ public static void sort(int[] data) { for (int i = 0; i < data.length; i++) { int index = i; for (int j = data.length - 1; j > i; j--) { if (data[j] < data[index]) { index = j; } } swap(data, i, index); } } private static void swap(int[] data, int a, int b) { int temp = data[a]; data[a] = data[b]; data[b] = temp; } public static void main(String[] args) { int[] data = new int[] { 3, 5, 55, 34, 67, 3, 78, 3423, 675, 4567 }; sort(data); System.out.print("Select sort result is: {"); for (int temp : data) { System.out.print(temp + " "); } System.out.print("}"); }}