冒泡排序和快速排序算法学习归纳-java实现


/**
* 冒泡排序和快速排序
*/
public class SwapSort {

public static void main(String[] args) {
int[] data = {261,53,48,11,13,48,32,15};

// bubbleSort(data);
quickSort(data);
for(int a: data){
System.out.print(a+" ");
}
}

/**
* 冒泡排序
*/
public static void bubbleSort(int[] r){
for(int i=1; i< r.length; i++){//n-1次循环
for(int j=0; j< r.length - i; j++){//逐步缩小冒泡范围
if(r[j] > r[j+1]){
int temp = r[j];
r[j] = r[j+1];
r[j+1] = temp;
}
}
}
}

/**
* 快速排序
*/
public static void quickSort(int[] r){
quickSort(r, 0, r.length -1);
}
/**
* 快速排序
*/
public static void quickSort(int[] r, int low, int high){
if(low < high){
int pa = partition(r, low, high);
quickSort(r, low, pa - 1);
quickSort(r, pa + 1, high);
}
}

/**
* 划分
*/
private static int partition(int[] r, int low, int high){
int pivot = r[low];//数轴元素
while(low < high){//从两端交替向内扫描
while(low < high && r[high] >= pivot){
high--;
}
r[low] = r[high];//将比pivot小的元素移向低端
while(low < high && r[low] <= pivot){
low++;
}
r[high] = r[low];//将比pivot大的元素移向高端
}
r[low] = pivot;//设置数轴
return low;//返回数轴元素位置
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值