Bubble sort and simple selection sort of Java collections

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);

	}
// 冒泡排序方法块(封装为一个方法通过主函数调用)
public void bubbleSort(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+" ");
		}
	}

Insert picture description here

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);
	}

public void selectSort(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 + " ");
		}

	}

Insert picture description here

Guess you like

Origin blog.csdn.net/fdbshsshg/article/details/113357883
Recommended