1.代码
package com.xtm.java.test;
/**
* Author: TianMing.Xiong
* Date: Created in 18-3-7 下午4:34
*/
public class SynchronzedTest {
public static void main(String args[]) {
int array[]={12, 10, 11, 7, 6, 5, 4, 3, 2, 1};
printArray(array);
// fastSortArray(array,0,array.length-1);
// selectSort1(array);
// bubbleSort(array);
insertSort(array);
System.out.println();
printArray(array);
}
/**
* 插入排序
* @param array
*/
private static void insertSort(int[] array) {
// for(int i=1;i<array.length;i++){
// int mValue=array[i];
// int j;
// for(j=i;j>0 && mValue<array[j-1];j--){
// array[j]= array[j-1];
// }
// array[j]=mValue;
// }
for(int i =1;i<array.length;i++){
int temp = array[i];
int j = i;
while(j>0 && temp < array[j-1] ){
array[j] = array[j-1];
j--;
}
array[j] = temp;
}
}
/**
* 冒泡排序
* @param array
*/
private static void bubbleSort(int[] array) {
for(int i=0;i<array.length-1;i++){
for(int j=0;j<array.length-i-1;j++){
if(array[j]>array[j+1]){
int tmp = array[j];
array[j]=array[j+1];
array[j+1]=tmp;
}
}
}
}
/**
* 选择排序
* @param array
*/
private static void selectSort1(int[] array) {
int len = array.length;
for(int i=0;i<len-1;i++){
//1.假设第一个元素值最小,取一个杯子min装这个最小的值
int min = array[i];
//2.从后面的元素中一一和最小元素比较,若比最小元素的值还小就进行交换(确保这个min值最小,且不破坏原数组数据)
for (int j=i+1;j<len;j++){
if(array[j]<min){
int tmp = min;
min=array[j];
array[j]=tmp;
}
}
//3.把这轮选择的最小的值赋值给当前元素
array[i] = min;
}
}
/**
* 选择排序
* @param array
*/
private static void selectSort2(int[] array) {
int len = array.length;
for(int i=0;i<len-1;i++){
//找出最小值的元素下标
int minIndex = i;
for (int j=i+1;j<len;j++){
if(array[j]<array[minIndex]){
minIndex=j;
}
}
//如果不是当前元素就进行交换
if(minIndex!=i){
int tmp=array[minIndex];
array[minIndex]=array[i];
array[i]=tmp;
}
}
}
/**
* 快速排序
* @param array
* @param firstIndex
* @param lastIndex
*/
private static void fastSortArray(int[] array, int firstIndex, int lastIndex) {
int i=firstIndex;
int j=lastIndex;
int temp = 0;
if(i>j){
return;
}
int base = array[firstIndex];
while (i<j){
//从右边找出小于基准下标
while (base<=array[j] && i<j){
j--;
}
//从左边找到大于基准下标
while (base>=array[i] && i<j){
i++;
}
//交换这两个值
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
//碰撞了就把当前值和基准值交换
int t=array[i];
array[i]=base;
array[firstIndex]=t;
//继续排序
fastSortArray(array,0,i-1);
fastSortArray(array,j+1,lastIndex);
}
/**
* 打印数组
* @param array
*/
private static void printArray(int[] array) {
for (int i=0;i<array.length;i++){
if(i!=array.length-1){
System.out.print(array[i]+"--");
}else {
System.out.print(array[i]);
}
}
}
}