1、冒泡排序的java实现
public class BubbleSort {
private int[] nums;
public BubbleSort(int size) {
this.nums = new int[size];
}
public String bubbleSort(int[] Nums) {
try {
this.nums = Nums;
if (Nums.length == nums.length) {
int temp = 0;// 充当临时变量
// long starTime=System.currentTimeMillis();//获取开始时间
for (int i = 0; i < this.nums.length; i++) {// 我们至多需要nums.length次就可以把所有的数排序好
for (int j = 0; j < this.nums.length - i - 1; j++) {// 每一次都有最大的数沉底
if (nums[j] > nums[j + 1]) {
temp = nums[j + 1];
nums[j + 1] = nums[j];
nums[j] = temp;
}
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
return null;
}
}
2、快速排序的java实现
public class QuickSort {
private int[] nums;
public QuickSort(int size) {
this.nums = new int[size];
}
public String quickSort(int[] Nums, int left, int right) {
// 如果left等于right,即数组只有一个元素,直接返回
this.nums = Nums;
if (left >= right) {
return null;
}
// 设置最左边的元素为基准值
int key = nums[left];
// 数组中比key小的放在左边,比key大的放在右边,key值下标为i
int i = left;
int j = right;
//i,j代表定位的指针
while (i < j) {
// j向左移,直到遇到比key小的值
while (nums[j] >= key && i < j) {
j--;
}
// i向右移,直到遇到比key大的值
while (nums[i] <= key && i < j) {
i++;
}
// i和j指向的元素交换
if (i < j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
nums[left] = nums[i];
nums[i] = key;
quickSort(nums, left, i - 1);
quickSort(nums, i + 1, right);
return null;
}
}
3、主程序Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("请输入排序数组的数据量:");
Scanner scan = new Scanner(System.in);
long starTime = 0;
long endTime = 0;
long Time = 0;
int n = 0;
int[] bubble_Nums;
int[] quick_Nums;
if (scan.hasNext()) {
n = scan.nextInt();
// 新建一个一百万的数组
bubble_Nums = new int[n];
quick_Nums = new int[n];
for (int i = 0; i < n; i++) {
int num = (int) (Math.random() * (n));
bubble_Nums[i] = num;
quick_Nums[i] = num;
}
starTime = System.nanoTime();//获取开始时间
BubbleSort bs = new BubbleSort(n);
System.out.print("冒泡排序运行时间:");
bs.bubbleSort(bubble_Nums);// 似乎不能直接在方法中直接传入{8,10,9,11,6,5,7}
endTime = System.nanoTime();; //获取结束时间
Time = endTime-starTime;
System.out.println(Time+"纳秒");
starTime = System.nanoTime();//获取开始时间
QuickSort qs = new QuickSort(n);
System.out.print("快速排序运行时间:");
qs.quickSort(quick_Nums, 0, n - 1);
endTime = System.nanoTime(); //获取结束时间
Time = endTime-starTime;
System.out.println(Time+"纳秒");
}
scan.close();
}
}
4、运行结果及目录结构
5、总结
我用同一个数组来比较,总的来说快排比冒泡是要快的。但在遇到特殊情况,比方说,以及按照从小到大排序好的数组输入快排中,算法中的递归会导致栈空间的溢出(Stack Overflow)。
这几天我在一直整理过去学习的知识,并以博客的形式呈现。如果对你有帮助,请点个赞,你的支持是我持续创作的动力~,有错误也请指出,谢谢。
另:博主会不定期更新,转载请注明出处!