交换排序
1冒泡排序-----具有稳定性-----o(n)–O(n2)
两辆相比,每次找出最大或者最小的放到最终的位置,
2快排------不具有稳定性
递归每次找出最中间的那个数,放到最终的位置,直到剩余一个或者0个元素.
(1) 时间复杂度: o(n* log2n) —O(n *n)
-
取决于划分操作的好坏,操作中枢轴的确定等,
-
后面的log2n -n就是二分查找树的最小高度和最大高度
**(2)*空间复杂度, O(log2n)-----O(n)
- 取决于递归的深度.也就是树的高度,
冒泡排序
//增序
public static void bubbleSort(int[] arr ){
int n = arr.length;
//这里i---n-1次
for (int i = 0; i < n-1; i++) {
boolean flag = false;
for (int j = n-1; j >i; j--) {
if (arr[j - 1] > arr[j]) {
//swap(arr[j-1],arr[j]);
int temp = arr[j-1];
arr[j-1] =arr[j];
arr[j] = temp;
}
flag = true;
}
if(flag==false){
return;
}
}
}
快速排序
pivot:枢轴
partition:分割
/*快排
*/
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
//划分函数
int pivotpoint = partition (arr,low ,high);
quickSort(arr, low, pivotpoint - 1);
quickSort(arr,pivotpoint+1,high);
}
}
//划分个分割函数,使得成每一个子表
public static int partition(int[] arr, int low, int high) {
//定义中枢轴值
int pivot = arr[low];
while(low <high) {
while ( low<high&& arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low<high&& arr[low] <=pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] =pivot;
return low;
}
}
总的(2个)
package Demo01;
public class demo03SwapSort {
public static void main(String[] args) {
int[] A = new int[]{21, 3, 54, 4, 7, 64, 9, 3};
//bubbleSort(A);
quickSort(A,0,A.length-1);
for (int a : A
) {
System.out.print(a + ",");
}
}
/*
交换排序----冒泡排序 --递增排序
*/
//
public static void bubbleSort(int[] arr ){
int n = arr.length;
for (int i = 0; i < n; i++) {
boolean flag = false;
for (int j = n-1; j >i; j--) {
if (arr[j - 1] > arr[j]) {
int temp = arr[j-1];
arr[j-1] =arr[j];
arr[j] = temp;
}
flag = true;
}
if(flag==false){
return;
}
}
}
/*快排
*/
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
//划分函数
int pivotpoint = partition (arr,low ,high);
quickSort(arr, low, pivotpoint - 1);
quickSort(arr,pivotpoint+1,high);
}
}
//划分个分割函数,使得成每一个子表
public static int partition(int[] arr, int low, int high) {
//定义中枢轴值
int pivot = arr[low];
while(low <high) {
while ( low<high&& arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low<high&& arr[low] <=pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] =pivot;
return low;
}
}