- 题目:
- 给定一个一维整型数组,自己实现冒泡排序、简单选择排序、快速排序完成对其的升序排列并输出?
- 答案
- 冒泡排序按降序排列
public class TestBubbleSort { public static void main(String[] args) { int[] arr={6,3,8,2,9,1}; System.out.println("排序前数组为:"); for(int num:arr){ System.out.print(num+" "); } for(int i=0;i<arr.length-1;i++){//外层循环控制排序趟数 ,最多循环array.length-1次 for(int j=0;j<arr.length-1-i;j++){//内层循环控制每一趟排序多少次 ,每趟最多比较arr.length-1-i次 if(arr[j]<arr[j+1]){ int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } System.out.println(); System.out.println("排序后的数组为:"); for(int num:arr){ System.out.print(num+" "); } } }
- 选择排序从前往后去顺序比较
public class TestSelectSort { public static void selectSort(int[] numbers) { int size = numbers.length; //数组长度 int temp = 0 ; //中间变量 for(int i = 0 ; i < size-1 ; i++) { int k = i; //待确定的位置 //选择出应该在第i个位置的数 for(int j=i+1; j<=size-1; j++) { if(numbers[j] < numbers[k]) { k = j; } } //交换两个数 temp = numbers[i]; numbers[i] = numbers[k]; numbers[k] = temp; } } public static void main(String[] args){ int[] noSortArray={9,38,2,22,88,10}; for(int old:noSortArray){ System.out.print(old+" "); } selectSort(noSortArray); System.out.println(); for(int newVal:noSortArray){ System.out.print(newVal+" "); } } }
- 快速排序
public class TestQuickSort { public static void quickSort(int[] intArray,int low,int high){ if(low>=high){ return; } int low_temp=low; int high_temp=high; int base=intArray[low_temp]; //约定执行条件 while(low<high){ //从右往左走,找到小于基准值的停下 while(low<high && intArray[high]>=base){ high--; } //从左往右走,找到大于基准值的停下 while(low<high && intArray[low]<=base){ low++; } //交换low和high值 if(low<high){ int temp=intArray[low]; intArray[low]=intArray[high]; intArray[high]=temp; } } //交换low和基准值 if(low_temp!=low){ intArray[low_temp]=intArray[low]; intArray[low]=base; } //左右各自递归循环 quickSort(intArray,low_temp,low-1); quickSort(intArray,low+1,high_temp); } public static void main(String[] args) { int[] intArray={10,7,2,4,9,8,3,8,9,1}; TestQuickSort.quickSort(intArray,0,intArray.length-1); for(int temp:intArray){ System.out.print(temp+" "); } } }
Java之常用三大排序(冒泡排序,简单选择排序,快速排序)
最新推荐文章于 2024-09-11 22:48:33 发布