1、排序
class Sort {
//选择排序
void selectionsort(int array[], int low, int high){
for(int i = low; i <= high-1; i++){
for(int j = i+1; j <=high; j++){
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
//冒泡排序
void bubblesort(int array[],int length){
for(int i = 0; i <= length-1; i++){
for(int j = 0; j <= length-i-1; j++){
if(array[j] > array[j+1]){
int temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
}
//归并排序
void mergesort(int array[], int low, int high){
if(low < high){
int middle = (low + high)/2;
mergesort(array, low, middle);
mergesort(array, middle+1, high);
merge(array, low, middle, high);
}
}
void merge(int array[], int low, int mid, int high){
int helper[] = new int[array.length];
for(int i = low; i < high; i++){
helper[i] = array[i];
}
int current = low;
int helperLeft = low;
int helperRight = mid+1;
while(helperLeft <= mid && helperRight <= high){
if(helper[helperLeft] <= helper[helperRight]){
array[current++] = helper[helperLeft++];
}else{
array[current++] = helper[helperRight++];
}
}
int remain = mid - helperLeft;
for(int i = 0; i <= remain; i++){
array[current + i] = helper[helperLeft+i];
}
}
//快速排序
void quicksort(int array[], int left, int right){
int index = partition(array, left, right);
if(left < index-1){
quicksort(array, left, index-1);
}else{
quicksort(array, index, right);
}
}
int partition(int array[], int left, int right){
int piovt = array[(left+right)/2];
while(left < right){
while(array[left] < piovt) left++;
while(array[right] > piovt) right--;
if(left <= right){
int temp = array[left];
array[left] = array[right];
array[right] = temp;
left++;
right--;
}
}
return left;
}
}
2、查找
class Search {
int binarySearch(int a[], int x){
int low = 0;
int high = a.length - 1;
int mid;
while(low <= high){
mid = (low + high)/2;
if(a[mid] > x){
low = mid + 1;
}else if(a[mid] < x){
high = mid - 1;
}else{
return mid;
}
}
return -1;
}
}