冒泡排序
排序思想:通过一趟排序将最小的数升至最上层。
void BubbleSort(Sqlist &L){
for(i=1;i<=L.length;++i){
for(j=L.length;j>i;j--){
if(L.r[j]<L.r[j-1]){
L.r[j]<->L.r[j-1];
}
}
}
思想2:将大数沉底:
private void bubleSort(int[] array) {
int len=array.length;
for (int i = len; i >0; i--) {
for (int j = 0; j < i-1; j++) {
if (array[j] > array[j + 1]) {
int tmp=array[j];
array[j]=array[j+1];
array[j+1]=tmp;
}
}
}
println(array);
}
快速排序
排序思想:通过一趟排序将顺序表分割成两部分,一部分始终小于另一部分,直到排序完成。
int Partition(Sqlist &L,int low,int high){
L.r[0]=L.r[low];
while(low<high){
while(low<high&&RT(L.r[high],L.r[low]){ --high;}
L.r[low]<->L.r[high];
while(low<high&<(L.r[low],L.r[high]) {++low}
L.r[low]<->L.r[high];
}//if
return low;
}
void QuickSort(Sqlist &L,int low,int high){
if(low<high){
int pivotkey=Partition(L,1,L.length);
QuickSort(L,low,pivotkey-1);
QuickSort(L,pivotkey+1,high);
}//if
}
Java实现:
private void quickSort(int[] array,int start ,int end){
if (start < end) {
int next = exchange(array, start, end);
quickSort(array, start, next-1);
quickSort(array, next+1, end);
}
///println(array);
}
private int exchange(int[] array,int start,int end) {
int target = array[start];
while (start < end) {
while (start<end&&target<=array[end])end--;
int tmp = array[start];
array[start] = array[end];
array[end] = tmp;
while (start<end&&target>=array[start]) start++;
int tmp1 = array[start];
array[start] = array[end];
array[end] = tmp1;
}
return start;
}
网友评论