冒泡排序
public class BubbleSort {
public static void sort(int[] data, int n) {
int sortedNum = 0;
int index;
while (sortedNum < n) {
for (index = 1; index < n - sortedNum; index++) {
if (data[index - 1] > data[index]) {
int tmp;
tmp = data[index - 1];
data[index - 1] = data[index];
data[index] = tmp;
}
}
sortedNum++;
}
}
}
选择排序
public class SelectSort {
public static void sort(int[] data, int n) {
int sortedNum = 0;
int index;
int maxIndex = 0;
while (sortedNum < n) {
for (index = 1; index < n - sortedNum - 1; index++) {
if (data[maxIndex] < data[index]) {
maxIndex = index;
}
}
int tmp;
tmp = data[maxIndex];
data[maxIndex] = data[n - sortedNum - 1];
data[n - sortedNum - 1] = tmp;
sortedNum++;
}
}
}
插入排序
public class InsertSort {
public static void sort(int[] data, int n) {
int sortedNum = 1;
int index;
while (sortedNum < n) {
int tmp = data[sortedNum];
for (index = sortedNum; index > 0; index--) {
if (tmp < data[index - 1]) {
data[index] = data[index - 1];
} else {
break;
}
}
//插入的他的位置
//index就是找TMP的位置
data[index] = tmp;
sortedNum++;
for(int i=0;i<n;i++){
System.out.print(data[i]+",");
}
System.out.println("");
}
}
}
快速排序
public class QuickSort {
public static void sort(int[] data, int n) {
quickSortRescursive(data, 0, n - 1);
}
private static void quickSortRescursive(int[] data, int left, int right) {
int pos;
if (left >= right)
return;
pos = getPos(data, left, right);
// 排左边的
quickSortRescursive(data, left, pos - 1);
quickSortRescursive(data, pos + 1, right);
}
private static int getPos(int[] data, int left, int right) {
// 想左边移动
while (true) {
//遇到右边的大就忽略,并且缩小右边范围
while (left < right && data[left] < data[right])
right--;
//遇到左边的大就往右边换
if (left < right)
swap(data, left++, right);
else
return left;
// 遇到右边的大就忽略,并且左边缩小范围
while (left < right && data[left] < data[right])
left++;
if (left < right)
//遇到左边的大就往右边换
swap(data, left, right--);
// return left;
else
return right;
// return 0;
}
}
private static void swap(int[] data, int i, int j) {
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
posted on 2006-05-25 15:07
小小程序程序员混口饭吃 阅读(373)
评论(0) 编辑 收藏 所属分类:
java