JAVA:冒泡排序,选择排序,插入排序和Shell排序

 
 
public class 冒泡排序 {
	public static void main(String[] args) {
		int a[] = { 1, 9, 6, 8, 5, 65, 65, 84, 1, 2, 5, 23, 7, 889 };
		for (int i = 0; i < a.length - 1; i++) {						//使用两个for循环遍历
			for (int j = 0; j < a.length - i - 1; j++) {				//减i是为了防止输出已经比较好的
				if (a[j] > a[j + 1]) {									//如果前面的数大于后面的数,则进行交换
					int temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
				}
			}
		}
		System.out.println(Arrays.toString(a));
	}
}


 

冒泡排序:基本思想:对比相邻的元素值,如果满足条件就交换元素值,把比较小的元素移动到数组前面,把比较大的移动到数组后面。

public class 选择排序 {
	public static void main(String[] args) {
		int array[] = { 63, 4, 24, 1, 3, 15 };
		int index;
		for (int i = 1; i < array.length; i++) {
			index = 0;
			for (int j = 1; j <= array.length - i; j++) {		//循环
				if (array[j] > array[index]) {						
					index = j;									//获取一个循环内最大元素
				}
			}
			int temp = array[array.length - i];					//将最大元素放到数组最后面	
			array[array.length - i] = array[index];				
			array[index] = temp;
		}
		System.out.println(Arrays.toString(array));
	}
}

选择排序基本思想:将指定排序位置与其他数组元素分别对比,如果满足条件就交换元素值,这里不是交换元素值,而是把满足条件的元素与指定位置的排序位置交换。

public class 插入排序 {

	public static void main(String[] args) {
		int[] array = { 56, 5, 185, 56, 8, 646, 589, 63, 846, 351656, 6516, 654465 };
		int i, j, t;
		for (i = 1; i < array.length; i++) {
			t = array[i];
			j = i - 1;
			while (j >= 0 && t < array[j]) {
				array[j + 1] = array[j];
				j--;
			}
			array[j + 1] = t;
		}
		for (int q = 0; q < array.length; q++) {
			System.out.print(array[q] + " ");
		}
	}
}

插入排序基本思想:先从数组中取出前两个数据,比较。在依次取出一个,与前两个比较比某个数大的放右边,比其小的放左边



public class Shell排序 {
	public static void main(String[] args) {
		int array[] = { 1, 5, 85, 416, 74, 123, 68, 46, 4, 68, 4, 61 };
		int j, temp;
		for (int r = array.length / 2; r >= 1; r /= 2) {
			for (int i = r; i < array.length; i++) {
				temp = array[i];
				j = i - r;
				while (j >= 0 && temp < array[j]) {
					array[j + r] = array[j];
					j -= r;
				}
				array[j + r] = temp;
			}
		}

		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");
		}
	}
}

Shell排序的基本思想:将n个元素分成n/2个数字序列,第1个和第n/2+1个数据为一对,每次循环使每个序列排号,再变成n/4个,再次排序。多次重复,直到序列减少到最后变成一个。

猜你喜欢

转载自blog.csdn.net/qq_42192693/article/details/80938172