参考代码如下,可以按需求自己修改
import java.util.Datepublic class SortThread {
public static void main(String[] args) {
//产生一个随机数组
int[] ary = getArray()
//启动冒泡排序线程
new Thread(new MaoPao(ary)).start()
//启动快速排序线程
new Thread(new KuaiSu(ary)).start()
}
private static int[] getArray() {
//建议数字n不要超过1百万,十万左右就好了
int n = (int) (Math.random()*1000000)+11
int[] ary= new int[n]
System.out.println("n的值是" + n)
for (int i = 0 i < ary.length i++) {
ary[i] = (int) (Math.random()*100000)
}
return ary
}
}
//冒泡排序
class MaoPao implements Runnable {
int[] ary
public MaoPao(int[] ary) {
this.ary = ary
}
@Override
public void run() {
long st = System.currentTimeMillis()
System.out.println(new Date() + "冒泡排序线程:开始执行排序")
for (int i = 0 i < ary.length - 1 i++) {
for (int j = 0 j < ary.length - i - 1 j++) {
if (ary[j] < ary[j + 1]) {
int temp = ary[j]
ary[j] = ary[j + 1]
ary[j + 1] = temp
}
}
}
long et = System.currentTimeMillis()
System.out.println(new Date() + "冒泡排序线程完成丛碧排序,耗费时间" + (et - st) + "毫秒")
for (int i = 0 i <凳郑棚 ary.length i++) {
System.out.println(ary[i]+" ")
}
}
}
//快速排序
class KuaiSu implements Runnable {
int[] ary
public KuaiSu(int[] ary) {
this.ary = ary
}
@Override
public void run() {
long st = System.currentTimeMillis()
System.out.println(new Date() + "快速排序线程:开始执行排序")
quickSort(ary, 1, ary.length)
long et = System.currentTimeMillis()
System.out.println(new Date() + "快速排序线程排序完成,耗费时间" + (et - st) + "毫秒")
for (int i = 0 i < ary.length i++) {
System.out.println(ary[i]+" ")
}
}
public static int Partition(int a[], int p, int r) {
int x = a[r - 1]
int 枣则i = p - 1
int temp
for (int j = p j <= r - 1 j++) {
if (a[j - 1] <= x) {
i++
temp = a[j - 1]
a[j - 1] = a[i - 1]
a[i - 1] = temp
}
}
temp = a[r - 1]
a[r - 1] = a[i + 1 - 1]
a[i + 1 - 1] = temp
return i + 1
}
public static void quickSort(int a[], int p, int r) {
if (p < r) {
int q = Partition(a, p, r)
quickSort(a, p, q - 1)
quickSort(a, q + 1, r)
}
}
}
importjava.util.Scanner\x0d\x0apublicclassMaoPao\x0d\x0a{\x0d\x0apublicstaticvoidmain(String[]args)\x0d\x0a{\x0d\x0aScannerscan=newScanner(System.in)\x0d\x0aint[]arr=newint[10]\x0d\x0a\x0d\x0a//把要排序的数值输入\x0d\x0afor(inti=0i欢迎分享,转载请注明来源:内存溢出
评论列表(0条)