How to use bubble sort and simple selection sort in java to sort an array of basic data types
The two most commonly used methods for sorting basic data types are bubble sort and simple selection sort
Bubbling sort: Its basic principle is to compare two adjacent numbers and swap the larger ones in order to go down to the end. The following shows some.
内联代码片
// 测试代码块
public static void main(String[] args) {
TestCsdn1 test = new TestCsdn1();
int[] array = {1,2,5,0,6,9,14,12,63};
test.bubbleSort(array);
}
// 冒泡排序方法块(封装为一个方法通过主函数调用)publicvoidbubbleSort(int[] array){
//先遍历数组for(int i =0; i < array.length; i++){
//再利用一个for循环比较相邻的两个数for(int j =0; j < array.length-1-i; j++){
//判断大小并交换位置if(array[j]>array[j+1]){
int temp = array[j];
array[j]= array[j+1];
array[j+1]= temp;}}}//把交换位置后的数组重新遍历出来for(int m : array){
System.out.print(m+" ");}}
Simple selection and sorting: The basic principle is that the first and subsequent comparisons encounter a larger number and exchange positions, then the exchanged number is compared with the following books in turn, and then exchanged until the end. The following shows some
内联代码片。
public static void main(String[] args) {
TestCsdn1 test = new TestCsdn1();
int[] array = { 1, 2, 5, 0, 6, 9, 14, 12, 63 };
test.selectSort(array);
}
publicvoidselectSort(int[] array){
for(int i =0; i < array.length-1; i++){
for(int j = i +1; j < array.length; j++){
if(array[j]<array[i]){
int temp = array[j];
array[j]= array[i];
array[i]= temp;}}}for(int m : array){
System.out.print(m +" ");}}