Javaの一般的なソート、バブル、選択、挿入、スナップ
2941 ワード
package sort;
public class MySort {
private int[] array;
private int length;
/**
*
* @param array
*/
public MySort(int[] array){
this.array = array;
this.length = array.length;
}
/**
*
*/
public void display(){
for(int i : array){
System.out.print(i+" ");
}
System.out.println();
}
public static void main(String[] args){
int[] array = {77,44,11,23,45,90,43,65,7,89,42,29,28,36,33,25,10,10,33,100};
// int[] array = {77,44,11,23,45,90,43,65,7};
MySort mySort = new MySort(array);
System.out.println(" :");
mySort.display();
mySort.quickSort(0,array.length - 1);
System.out.println(" :");
mySort.display();
}
/**
*
*/
private void bobSort() {
for(int i = 0 ; i < array.length - 1 ; ++ i ){
for (int j = i + 1 ; j < array.length ; ++j ){
if(array[i] > array[j]){
int t = array[i];
array[i] = array[j];
array[j] = t;
}
}
}
}
/**
*
*/
private void selectSort() {
for (int i = 0; i < array.length - 1; ++i) {
int minIndex = i;
for (int j = i + 1; j < array.length; ++j) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
int t = array[i];
array[i] = array[minIndex];
array[minIndex] = t;
}
}
/**
*
*/
private void insertSort(){
for (int i = 1 ; i < array.length ; ++ i){
int temp = array[i];
int leftIndex = i - 1;
while ( leftIndex >= 0 && array[leftIndex] > temp ){
array[leftIndex+1] = array[leftIndex];
--leftIndex;
}
array[leftIndex+1] = temp;
}
}
/**
*
*/
private void quickSort(int low ,int high){
if(low >= high){
return ;
}
int left = low;
int right = high;
int temp = array[left];
int t;
while (left < right){
//
while( temp <= array[right] && left < right){
-- right ;
}
//
while ( temp >= array[left] && left < right){
++ left;
}
if(left < right){
t = array[left];
array[left] = array[right];
array[right] = t;
}
}
array[low] = array[left];
array[left] = temp;
quickSort(low,left - 1);
quickSort(left + 1,high);
}
}