复习排序算法

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int num = scanner.nextInt();
		int[] array = new int[num];
		for (int i = 0; i < num; i++) {
			array[i] = scanner.nextInt();
		}
		Main main = new Main();
		// main.bubbleSort(array);
		// for (int i : array) {
		// System.out.print(i+" ");
		// }

		// main.insertSort(array);
		// for (int i : array) {
		// System.out.print(i+" ");
		// }
		main.shellSort(array);
	}

	// 冒泡排序,算法时间复杂度是O(N^2)
	private void bubbleSort(int[] array) {
		int temp = 0;
		for (int i = 0; i < array.length - 1; i++) {
			for (int j = i + 1; j < array.length; j++) {
				if (array[i] > array[j]) {
					temp = array[j];
					array[j] = array[i];
					array[i] = temp;
				}
			}
		}

	}

	// 直接插入排序,每次插入都要跟前面已经排好序的相比较,算法时间复杂度是O(N^2)
	private void insertSort(int[] array) {
		int temp = 0;
		for (int i = 1; i < array.length; i++) {
			for (int j = i; j > 0; j--) {
				if (array[j] < array[j - 1]) {
					temp = array[j];
					array[j] = array[j - 1];
					array[j - 1] = temp;
				}
			}
		}
	}

	/*
	 * 希尔排序(shell排序),插入排序中的一种,思路是将数据分组,然后对每一小组数据
	 * 进行冒泡排序,然后对所有的小组最后进行一次直接插入排序就可以达到目的。如此的好处
	 * 就是加快速度,减少数据交换的次数。希尔排序的时间复杂度与增量序列的选取有关 步骤是:先取一个小于n的整数d1作为第一个增量,把文件的全部记录分组。
	 * 所有距离为d1的倍数的记录放在同一个组中。先在各组内进行直接插入排序; 然后,取第二个增量d2<d1重复上述的分组和排序,直至所取的增量
	 * dt=1(dt<dt-l<…<d2<d1),即所有记录放在同一组中进行直接插入排序为止。
	 */
	private void shellSort(int[] array) {
		System.out.print("排序之前:");
		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");

		}
		int d = array.length;
		int count = 0;
		int countNum = 0;
		while (d!=1) {
			d = d / 2;
			countNum = 0;
			for (int x = 0; x < d; x++) {
				for (int i = x + d; i < array.length; i = i + d) {
					int temp = array[i];
					int j;
					for (j = i - d; j >= 0 && array[j] > temp; j = j - d) {
						array[j + d] = array[j];
						countNum ++;
						System.out.println();
						System.out.println(temp+"与"+array[j + d]+"交换");
					}
					array[j + d] = temp;
				}
			}
			count++;
			System.out.println();
			System.out.print("第"+count+"次排序之后:");
			for (int i = 0; i < array.length; i++) {
				System.out.print(array[i] + " ");

			}
			System.out.print("比较次数"+countNum);
		}

		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值