// 歸併排序 需要佔用額外空間
public static int[] sort(int[] a,int low,int high){
int mid = (low+high)/2;
if(low<high){
sort(a,low,mid);
sort(a,mid+1,high);
//左右歸併
merge(a,low,mid,high);
}
return a;
}
public static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high-low+1];
// 低位指針
int i= low;
// 高位指針
int j = mid+1;
// 新建數組 指針
int k=0;
// 把較小的數先移到新數組中
while(i<=mid && j<=high){
if(a[i]<a[j]){
temp[k++] = a[i++];
}else{
temp[k++] = a[j++];
}
}
// 把左邊剩餘的數移入數組
while(i<=mid){
temp[k++] = a[i++];
}
// 把右邊邊剩餘的數移入數組
while(j<=high){
temp[k++] = a[j++];
}
// 把新數組中的數覆蓋nums數組
for(int x=0;x<temp.length;x++){
a[x+low] = temp[x];
}
}
// 快速排序
public static int partition(int []array,int lo,int hi){
//三數取中
int mid=lo+(hi-lo)/2;
if(array[mid]>array[hi]){
swap(array[mid],array[hi]);
}
if(array[lo]>array[hi]){
swap(array[lo],array[hi]);
}
if(array[mid]>array[lo]){
swap(array[mid],array[lo]);
}
int key=array[lo];
while(lo<hi){
while(array[hi]>=key&&hi>lo){
hi--;
}
array[lo]=array[hi];
while(array[lo]<=key&&hi>lo){
lo++;
}
array[hi]=array[lo];
}
array[hi]=key;
return hi;
}
public static void swap(int a,int b){
int temp=a;
a=b;
b=temp;
}
public static void sort(int[] array,int lo ,int hi){
if(lo>=hi){
return ;
}
int index=partition(array,lo,hi);
sort(array,lo,index-1);
sort(array,index+1,hi);
}
// 選擇排序 時間複雜度
public static void selectionSort(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int k = i;
// 找出最小值的下標
for (int j = i + 1; j < n; j++) {
if (a[j] < a[k]) {
k = j;
}
}
// 將最小值放到未排序記錄的第一個位置
if (k > i) {
int tmp = a[i];
a[i] = a[k];
a[k] = tmp;
}
}
}
// 冒泡排序,a 表示數組,n 表示數組大小
public void bubbleSort(int[] a, int n) {
if (n <= 1) {return; }
for (int i = 0; i < n; ++i) {
// 提前退出冒泡循環的標誌位
boolean flag = false;
for (int j = 0; j < n - i - 1; ++j) {
// 交換
if (a[j] > a[j+1]) {
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
// 表示有數據交換
flag = true;
}
}
// 沒有數據交換,提前退出
if (!flag){ break; }
}
}
// 插入排序,a 表示數組,n 表示數組大小
public void insertionSort(int[] a, int n) {
if (n <= 1) {return;}
for (int i = 1; i < n; ++i) {
int value = a[i];
int j = i - 1;
// 查找插入的位置
for (; j >= 0; --j) {
if (a[j] > value) {
// 數據移動
a[j+1] = a[j];
} else {
break;
}
}
// 插入數據
a[j+1] = value;
}
}
low+((high-low)>>1)
java中排序算法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.