【算法】排序

 1 package main;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileReader;
 6 import java.io.FileWriter;
 7 import java.util.*;
 8 import java.util.concurrent.ExecutorService;
 9 import java.util.concurrent.Executors;
10 import java.util.concurrent.locks.Condition;
11 import java.util.concurrent.locks.Lock;
12 import java.util.concurrent.locks.ReentrantLock;
13 
14 public class Main {
15     public static void main(String[] args) {
16         int[] array = {100, 0, 1, 2, 4, 3, 5, 4, 5, 6, 7, 8, 9, 10, 11, 12};
17 
18         //冒泡排序
19         for (int i = 0; i < array.length; i++) {
20             boolean flag = false;
21             for (int j = 0; j < array.length - i - 1; j++) {
22                 if (array[j] > array[j + 1]) {
23                     int temp = array[j];
24                     array[j] = array[j + 1];
25                     array[j + 1] = temp;
26                     flag = true;
27                 }
28             }
29             if (flag) {
30                 break;
31             }
32         }
33         System.out.println(Arrays.toString(array));
34 
35         int[] array_2 = {100, 0, 1, 2, 4, 3, 5, 4, 5, 6, 7, 8, 9, 10, 11, 12};
36         //简单选择排序
37         for (int i = 0; i < array.length; i++) {
38             int loc = i;
39             for (int j = i + 1; j < array.length; j++) {
40                 if (array_2[j] < array_2[loc]) {
41                     loc = j;
42                 }
43             }
44             if (loc != i) {
45                 int temp = array_2[i];
46                 array_2[i] = array_2[loc];
47                 array_2[loc] = temp;
48             }
49         }
50         System.out.println(Arrays.toString(array_2));
51 
52         int[] array_3 = {3,5,4,2,1,6,7,8};
53         //快速排序
54         quitSort(array_3,0,array_3.length-1);
55         System.out.println(Arrays.toString(array_3));
56 
57     }
58 
59     static void quitSort(int[] array, int left, int right) {
60         int i = left;
61         int j = right;
62         if (left >= right) {
63             return;
64         }
65         int base = array[i];
66         while (i < j) {
67             while (i < j && array[j] >= base) {
68                 j--;
69             }
70 
71             if (j > i) {
72                 array[i] = array[j];
73             }
74             while (i < j && array[i] <= base) {
75                 i++;
76             }
77             if (i < j) {
78                 array[j] = array[i];
79             }
80         }
81         array[i] = base;
82         quitSort(array,left,i-1);
83         quitSort(array,i+1,right);
84     }
85 }

 

posted @ 2018-08-18 10:40  程小白  阅读(109)  评论(0编辑  收藏  举报