題目:
- 給定一個一維整型數組,自己實現冒泡排序、簡單選擇排序、快速排序完成對其的升序排列並輸出?
答案
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+" ");
}
}
}