快速排序
快速排序的思想依据是分治法,选取第一个元素为对比值,然后将表中比对比值小的放在左边,将对比值大的放在右边,然后再将左边的列表用同样的方法进行排列,将右边的方法进行排列,依次递归下去,最终有序。下面列出java实现
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实现
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();
}
}
简单选择排序
算法思想:选取第一个作为标准值,然后对比后面的数,选取一个最大的,与第一个进行交换,position用于标记最大的数的位置。然后选择第二个数为标准值,然后依次进行下去。
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();
}
}