package com.wxh617.sort;
public class BubbleSort {
//测试用例
private static int[] a = {9,6,2,5,7,6};
public static void main(String[] args) {
bubbleSort3(a);
//bubbleSort1(a);
//bubbleSort2(a);
}
//1.最简单的冒泡排序算法,没有技术含量 本例中排序6趟
public static void bubbleSort1(int[] a) {
int length = a.length;
for (int i = 0; i <length; i++) {
for (int j = 0; j<length - i - 1; j++) {
int temp = 0;
if (a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
for (int k = 0; k < a.length; k++) {
System.out.print(a[k] + " ");
}
System.out.println();
}
}
//2.下面对其进行优化,设置一个标志,如果这一趟发生了交换,则为true,否则为false。明显如果有一趟没有发生交换,说明排序已经完成。
public static void bubbleSort2(int[] a){
int exchange = a.length;
while(exchange>0){
int bound = exchange;
exchange = 0;
for(int i =1;i<bound;i++){
if(a[i-1]>a[i]){
int temp = a[i-1];
a[i-1] = a[i];
a[i] = temp;
//记录每一次发生记录交换的位置
exchange = i;
}
}
System.out.println("一次排序的结果为 :"+exchange);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
//3.双向冒泡
public static void bubbleSort3(int[] a){
int left = 0;
int right = a.length-1;
int l=0,r=0;
while(left<right){
for(int i=left;i<right;i++){
if(a[i]>a[i+1]){
int temp = a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
r=i;
}
right = r;
for(int j=right;j>left;j--){
if(a[j]<a[j-1]){
int temp = a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
l=j;
}
left = l;
System.out.println("第次排序结果:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
}
public class BubbleSort {
//测试用例
private static int[] a = {9,6,2,5,7,6};
public static void main(String[] args) {
bubbleSort3(a);
//bubbleSort1(a);
//bubbleSort2(a);
}
//1.最简单的冒泡排序算法,没有技术含量 本例中排序6趟
public static void bubbleSort1(int[] a) {
int length = a.length;
for (int i = 0; i <length; i++) {
for (int j = 0; j<length - i - 1; j++) {
int temp = 0;
if (a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
for (int k = 0; k < a.length; k++) {
System.out.print(a[k] + " ");
}
System.out.println();
}
}
//2.下面对其进行优化,设置一个标志,如果这一趟发生了交换,则为true,否则为false。明显如果有一趟没有发生交换,说明排序已经完成。
public static void bubbleSort2(int[] a){
int exchange = a.length;
while(exchange>0){
int bound = exchange;
exchange = 0;
for(int i =1;i<bound;i++){
if(a[i-1]>a[i]){
int temp = a[i-1];
a[i-1] = a[i];
a[i] = temp;
//记录每一次发生记录交换的位置
exchange = i;
}
}
System.out.println("一次排序的结果为 :"+exchange);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
//3.双向冒泡
public static void bubbleSort3(int[] a){
int left = 0;
int right = a.length-1;
int l=0,r=0;
while(left<right){
for(int i=left;i<right;i++){
if(a[i]>a[i+1]){
int temp = a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
r=i;
}
right = r;
for(int j=right;j>left;j--){
if(a[j]<a[j-1]){
int temp = a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
l=j;
}
left = l;
System.out.println("第次排序结果:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}
}