对于一个int数组,请编写一个冒泡排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
import java.util.*;
public class BubbleSort {
public int[] bubbleSort(int[] A, int n) {
for(int i=0;i<n;i++){
for(int j=0;j<n-i-1;j++){
if(A[j]>A[j+1]){
int temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
}
}
}
return A;
}
}
对于一个int数组,请编写一个选择排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
import java.util.*;
public class SelectionSort {
public int[] selectionSort(int[] A, int n) {
// write code here
for(int i=0;i<n;i++){
int min=A[i];
int index=i;
for(int j=i+1;j<n;j++){
if(A[j]<min){
index=j;
min=A[j];
}
}
int temp=A[index];
A[index]=A[i];
A[i]=temp;
}
return A;
}
}
对于一个int数组,请编写一个插入排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
import java.util.*;
public class InsertionSort {
public int[] insertionSort(int[] A, int n) {
// write code here
for(int i=1;i<n;i++){
int now=i;
for(int j=i-1;j>=0;j--){
if(A[now]<A[j]){
int temp=A[now];
A[now]=A[j];
A[j]=temp;
now=j;
}
}
}
return A;
}
}
对于一个int数组,请编写一个归并排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
import java.util.*;
public class MergeSort {
public int[] mergeSort(int[] A, int n) {
// write code here
sort(A,0,n-1);
return A;
}
public void sort(int[]A,int left,int right){
int middle=(left+right)/2;
if(left<right){
sort(A,left,middle);
sort(A,middle+1,right);
comb(A,left,right,middle);
}
}
public void comb(int[]A,int left,int right,int middle){
int[]temp=new int[right-left+1];
int leftIndex=left;
int rightIndex=middle+1;
int tempIndex=0;
while(leftIndex<=middle&&rightIndex<=right){
if(A[leftIndex]<A[rightIndex]){
temp[tempIndex++]=A[leftIndex++];
}else{
temp[tempIndex++]=A[rightIndex++];
}
}
while(leftIndex<=middle){
temp[tempIndex++]=A[leftIndex++];
}
while(rightIndex<=right){
temp[tempIndex++]=A[rightIndex++];
}
int tem=0;
while((tem+left)<=right){
A[tem+left]=temp[tem];
tem++;
}
}
}