排序的三种方法
- 提问者网友:黑米和小志
- 2021-07-20 23:14
- 五星知识达人网友:梦中风几里
- 2021-07-20 23:41
直接选择算法:
public class SelectSort{
public static void selectSort(int[] a){
int i, j, small;
int temp;
int n = a.length;
for(i = 0; i < n - 1; i ++){
small = i; //设第i个数据元素最小
for(j = i + 1; j < n; j ++) //寻找最小的数据元素
if(a[j] < a[small]) small = j; //记住最小元素的下标
if(small != i){ //当最小元素的下标不为i时交换位置
temp = a[i];
a[i] = a[small];
a[small] = temp;
}
}
}
public static void main(String[] args){
int[] test = {64,5,7,89,6,24};
int n = test.length;
selectSort(test);
for(int i = 0; i < n; i++)
System.out.print(test[i] + " ");
}
}
冒泡算法:
public class BubbleSort{
public static void bubbleSort(int[] a){
int i, j, flag=1;
int temp;
int n = a.length;
for(i = 1; i < n && flag == 1; i++){
flag = 0;
for(j = 0; j < n-i; j++){
if(a[j] > a[j+1]){
flag = 1;
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
public static void main(String[] args){
int[] test = {64,5,7,89,6,24};
int n = test.length;
bubbleSort(test);
for(int i = 0; i < n; i++)
System.out.print(test[i] + " ");
}
}
快速排序算法:
public class QuickSort{
public static void quickSort(int[] a, int low, int high){
int i, j;
int temp;
i = low;
j = high;
temp = a[low]; //取第一个元素为标准数据元素
while(i < j){
//在数组的右端扫描
while(i < j && temp <= a[j]) j--;
if(i < j){
a[i] = a[j];
i++;
}
//在数组的左端扫描
while(i < j && a[i] < temp) i++;
if(i < j){
a[j] = a[i];
j--;
}
}
a[i] = temp;
if(low < i) quickSort(a, low, i-1); //对左端子集合递归
if(i < high) quickSort(a, j+1, high); //对右端子集合递归
}
public static void main(String[] args){
int[] test = {60,55,48,37,10,90,84,36};
int n = 8;
quickSort(test, 0, 7);
for(int i = 0; i < n; i++)
System.out.print(test[i] + " ");
}
}
然后在主函数里面创建对象,应用就好了!