Java排序可视化(冒泡+希尔+堆排+选择+递归)
1. 效果展示
all是五种排序同时进行,以便更好观察,文末会附图说明。
这里选择的是选择排序升序。
2. 思路+代码
在熟练掌握了这五种排序思想后,首先我们在Algorithm.java中写好排序算法的代码,同时写好GUI界面总体规划(GUI.java),实例化JFrame组件,为后面的主要界面设计(RandomGUI.java 、 ChoiceAlgorithm.java )做准备:
package com.Algorithm;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import com.GUI.GUI;
public class Algorithm {
private GUI g;//创建对象
public int[] a1;
ArrayList<String> syso = new ArrayList<String>();
String temp;
String filePath[] = new String[] {
"./冒泡排序.txt", "./希尔排序.txt", "./堆排序.txt", "./选择排序.txt", "./递归排序.txt", };
public static volatile int i = 0;
public static volatile int j = 0;
public Algorithm(int[] arr, String name, int k) {
this.g = new GUI(arr, 500 * i, 500 * j, name, k);
if (i == 2) {
j++;
i = 0;
}
i++;
}
public void write(File f) {
if (f.canRead()) {
f.delete();
}
if (!f.canRead()) {
try {
if (f.createNewFile()) {
new Exception("文件不能创建,请检查权限");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
for (String t : syso) {
bw.write(t);
bw.newLine();
bw.flush();
}
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void mySleep(int[] a) {
g.jpl.arr = a;
temp = "";
for (int a1 : a) {
temp += a1 + ",";
}
syso.add(temp);
g.jpl.setSyso(syso);
g.jpl.repaint();
try {
Thread.sleep(1500);// 延时刷新时间
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int[] maopao(int a[]) {
// 冒泡排序
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
mySleep(a);
}
}
}
File f = new File(filePath[0]);
write(f);
return a;
}
public int[] xier(int[] ins) {
//sort(ins);
// 希尔排序
int n = ins.length;
int gap = n / 2;
while (gap > 0) {
for (int j = gap; j < n; j++) {
int i = j;
while (i >= gap && ins[i - gap] > ins[i]) {
int temp = ins[i - gap] + ins[i];
ins[i - gap] = temp - ins[i - gap];
ins[i] = temp - ins[i - gap];
i -= gap;
mySleep(ins);
}
}
gap = gap / 2;
}
File f = new File(filePath[1]);
write(f);
return ins;
}
public void heapSort(int[] a) {
int len = a.length - 1;
// heapSort(b, b.length - 1);
// 推排序
int i;
for (i = len / 2; i >= 0; i--) {
/* 把a[]构造成一个大顶堆 */
HeapAdjust(a, i, len);
}
for (i = len; i > 0; i--) {
swap(a, 0, i); /* 交换堆顶最大元素和堆尾最小元素 */
HeapAdjust(a, 0, i - 1); /* 把交换后的堆a[0,i-1],再次构造成大顶顶,使堆顶元素为最大值 */
mySleep(a);
}
File f = new File(filePath[2]);
write(f);
}
private void HeapAdjust(int[] a, int start, int len) {
int temp, j;
temp = a[start];
for (j = 2 * start; j <= len; j *= 2) {
/* 从index最大的有孩子的节点开始筛选,堆排 */
if (j < len && a[j] < a[j + 1]) /* 是index=j的元素为较大的元素 */
j++;
if (temp >= a[j])
break;
a[start] = a[j]; /* 将较大元素赋值给父节点 */
start = j