Java 冒泡排序 并与 Arrays.sort(arr) 比较

版权声明:借鉴时注明出处就行 https://blog.csdn.net/weixin_42144379/article/details/84644769

前段时间收到一个猎头电话面试,问了关于冒泡排序的.我居然一时间想不起来...

只是回答了,大概俩个for循环什么的...

今天想起来,复习下:        jdk 1.8.0_181

package review;

import java.util.Arrays;

public class Jacktu{
	public static void bubble_sort(int[] arr) {
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = 0; j < arr.length - i - 1; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j + 1];
					arr[j + 1] = arr[j];
					arr[j] = temp;
				}
			}
		}
	}

	public static void main(String[] args) {
		int arrLength = 200000;
		int[] arr = new int[arrLength];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int) (Math.random() * arrLength);
		}
		int arr1[] = Arrays.copyOf(arr, arr.length);

		long start = System.currentTimeMillis();
		bubble_sort(arr);
		System.out.println(System.currentTimeMillis() - start);

		start = System.currentTimeMillis();
		Arrays.sort(arr1);
		System.out.println(System.currentTimeMillis() - start);

	}
}

结果:  冒泡排序花费 50326 ms

          Arrays.sort() 花费 30 ms

猜你喜欢

转载自blog.csdn.net/weixin_42144379/article/details/84644769