Taking the ascending integer sort as an example, a brief explanation of the process of bidirectional bubble sorting: first move the maximum number from front to back to the end, and then in turn move the smallest number from back to front to the front of the array. This process is In the first round, repeat this process and finally arrange the entire array from small to large. Two-way bubble sorting is slightly better than traditional bubble sorting, because both ends of the array are sorted well during bidirectional sorting, we only need to process the middle part of the array, while one-way, that is, traditional bubble sorting, only the elements at the tail. It is sorted, and each round of processing needs to be processed from the beginning to the previous element that has been sorted. Although it has improved a little in efficiency, it cannot significantly improve its sorting efficiency, which is determined by the basic process of bubble sorting. On this basis, it has been improved. The following code can realize the sorting of odd and even numbers separately.
Two-way bubble sorting source code:
The code copy is as follows:
package com.zc.manythread;
import java.util.Random;
/**
* Two-way bubble sort
* @author I'm
*
*/
public class BBSort {
//The bidirectional bubble algorithm greatly reduces the number of times of loop sorting
public int[] sort(int[] a)throws Exception{
int j;
int limit=a.length;
int st=-1;
while(st<limit){
//The st and limit must be assigned, otherwise if the array is ordered from the beginning
st++;
limit--;
boolean swapped=false;
//The first loop puts the maximum value to the end
for (j = st ; j < limit; j++) {
if (a[j]>a[j+1]) {
int T=a[j];
a[j]=a[j+1];
a[j+1]=T;
swapped=true;
}
}
if (!swapped) {
return a;
}else {
swapped=false;
//The second loop puts the minimum value at the beginning
for (j = limit; --j>=st;) {
if(a[j]>a[j+1]){
int T=a[j];
a[j]=a[j+1];
a[j+1]=T;
swapped=true;
}
}
if (!swapped) {
return a;
}
}
}
return a;
}
private static int[] createDate(int count) {
/**
* No duplicate array
*/
int[] data=new int[count];
Random rand = new Random();
boolean[] bool = new boolean[100];
int num = 0;
for (int i = 0; i < count; i++) {
do {
// If the generated number is the same, continue to loop
num = rand.nextInt(100);
} while (bool[num]);
bool[num] = true;
/* list.add(num);*///list list
data[i]=num;
}
return data;
}
public static void main(String[] args) {
final int count=10;
int[] data=createDate(count);
for(int n : data){
System.out.print(n+"/t");
}
System.out.println();
BSrot bsrot=new BSrot(data);
try {
int[] a=bsrot.sort(data);
for(int n : a){
System.out.print(n+"/t");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Running results: