快速排序
快速排序的思想依據(jù)是分治法畅涂,選取第一個元素為對比值,然后將表中比對比值小的放在左邊道川,將對比值大的放在右邊午衰,然后再將左邊的列表用同樣的方法進行排列立宜,將右邊的方法進行排列,依次遞歸下去臊岸,最終有序橙数。下面列出java實現(xiàn)
package arithmetic;
/**
* Created by elijahliu on 2017/3/2.
*/
public class QuickSort {
int a[] = {49,37,65,97,76,13,27,49,78};
public QuickSort(){
quickSort(a,0,a.length-1);
for (int i:a
) {
System.out.print(i+" ");
}
}
public int getMiddle(int[] list,int low,int high){
int temp = list[low];
while (low < high) {
while (low < high && list[high] >= temp) {
high--;
}
list[low] = list[high];
while (low < high && list[low] <= temp) {
low++;
}
list[high] = list[low];
}
list[low] = temp;
return low;
}
public void _quickSort(int[] list, int low, int high) {
if (low < high) {
int mid = getMiddle(list, low, high);
_quickSort(list, low, mid - 1);
_quickSort(list, mid + 1, high);
}
}
public void quickSort(int[] list, int low, int high) {
if (list.length > 0) {
_quickSort(list, low, high);
}
}
public static void main(String[] args) {
new QuickSort();
}
}
直接插入排序
直接插入排序的算法思想:從第二個元素開始,如果比前面的元素都小扇单,那么就將前面的元素往后移一位商模,然后把自己的值放到前面的位置上,最終由小到大排列蜘澜。
java實現(xiàn)
package arithmetic;
/**
* Created by elijahliu on 2017/3/2.
*/
public class InsertSort {
public InsertSort(){
insertSort();
}
int a[] = {49, 38, 65, 97, 76, 13, 27, 49};
public void insertSort(){
int temp = 0;
for(int i = 1;i<a.length;i++) {
temp = a[i];
int j = i - 1;
for(;j>=0&&temp<a[j];j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
for (int i:a
) {
System.out.println(i+" ");
}
}
public static void main(String[] args) {
new InsertSort();
}
}
冒泡排序
最簡單的冒泡排序,大一就學過了
package arithmetic;
/**
* Created by elijahliu on 2017/3/2.
*/
public class BubbleSort {
public BubbleSort() {
bubbleSort();
}
int a[] = {49, 38, 65, 97, 76, 13};
public void bubbleSort() {
int temp = 0;
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i : a
) {
System.out.println(i + "");
}
}
public static void main(String[] args) {
new BubbleSort();
}
}
簡單選擇排序
算法思想:選取第一個作為標準值响疚,然后對比后面的數(shù)鄙信,選取一個最大的,與第一個進行交換忿晕,position用于標記最大的數(shù)的位置装诡。然后選擇第二個數(shù)為標準值,然后依次進行下去践盼。
package arithmetic;
/**
* Created by elijahliu on 2017/3/2.
*/
public class SelectSort {
int a[] = {1, 54, 6, 3, 78, 34, 12, 45};
public SelectSort() {
seletctSort();
}
public void seletctSort() {
int position = 0;
for (int i = 0; i < a.length; i++) {
position = i;
int temp = a[i];
for (int j = i + 1; j < a.length; j++) {
if (a[j] > temp) {
temp = a[j];
position = j;
}
}
a[position] = a[i];
a[i] = temp;
}
for (int i : a
) {
System.out.print(i + " ");
}
}
public static void main(String[] args) {
new SelectSort();
}
}