Java 排序算法冒泡排序、插入排序、选择排序、奇偶排序、并行奇偶排序

本章将介绍一些常用的排序算法,有常用的串行排序,如冒泡排序、选择排序、插入排序、奇偶排序;还有对奇偶排序的并行实现方法。

一、串行排序

直接上代码

public class Sorts {

public static void main(String[] args) {
int[] array = {9,8,23,34,65,78,3,46,24};

// sortBubble(array); //冒泡

// selectSorts(array); //选择排序

// insertSorts(array);  //插入排序

oddEvenSorts(array); //奇偶排序


for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+"-");
}
}

/**
* 冒泡排序
* 2018年6月15日
* @param array
*/
private static void sortBubble(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j < array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}

/**
* 选择排序
* 2018年6月15日
* @param array
*/
private static void selectSorts(int[] array) {
for (int i = 0; i < array.length; i++) {
int min = i;
for (int j = i+1; j < array.length; j++) {
if (array[min] > array[j]) {
min = j;
}
}

if (array[i] > array[min]) {
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
}

/**
* 插入排序
* 2018年6月19日
* @param array
*/
private static void insertSorts(int[] array) {
for (int i = 1; i < array.length; i++) {
int temp = array[i];
int j ;
for (j = i-1; j>=0 && temp < array[j]; j--) {
array[j+1] = array[j];
}
array[j+1] = temp;
}
}

/**
* 奇偶排序
* 2018年6月27日
* @param array
*/
private static void oddEvenSorts(int[] array){
int flag = 1,start = 0;
while (flag == 1 || start == 1) {
flag = 0;
for (int i = start; i < array.length-1; i+=2) {
if (array[i] > array[i+1]) {
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
flag = 1;
}
}
if (start == 0) 
start = 1;
else 
start = 0;
}
}

}

二、并行排序

奇偶排序的并行实现方法,在串行奇偶排序的基础上进行改造。

/**
 * 并行 奇偶排序
 * 2018年6月27日
 */
public class OddEvenSorts {
static int[] array = {9,8,23,34,65,78,3,46,24};
private static int flag = 1;
public static synchronized int getFlag() {
return flag;
}

public static synchronized void setFlag(int flag) {
OddEvenSorts.flag = flag;
}

static class OddEvenTasks implements Runnable{
int i;
CountDownLatch latch ;
public OddEvenTasks(int i, CountDownLatch latch) {
this.i = i;
this.latch = latch;
}

@Override
public void run() {
if (array[i] > array[i+1]) {
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
setFlag(1);
}
latch.countDown();
}
}

public static void oddEvenSort(int[] array) throws InterruptedException{
int start = 0;
ExecutorService executorService = Executors.newCachedThreadPool(); //创建线程池
while (getFlag() == 1 || start == 1) {
setFlag(0);
CountDownLatch latch = new CountDownLatch(array.length/2-(array.length%2==0?start:0));
for (int i = start; i < array.length-1; i+=2) {
executorService.submit(new OddEvenTasks(i, latch));
}
latch.await();
if (start == 0) 
start = 1;
else 
start = 0;
}
}
public static void main(String[] args) throws InterruptedException  {
oddEvenSort(array);
for (int arr : array) {
System.out.print(arr+"-");
}
}
}

 

猜你喜欢

转载自blog.csdn.net/yin767833376/article/details/80825996