黑马学习日记2

来源:互联网 发布:mycard萌卡 mac 编辑:程序博客网 时间:2024/05/21 05:23

、黑马程序员-排序方法

 

------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------

JAVA中的排序算法一般主要有四种方法:快速排序法、冒泡法、选择排序法、插入排序法。

快速排序法主要是运用了Arrays中的一个方法Arrays.sort()实现。

冒泡法是运用遍历数组进行比较,通过不断的比较将最小值或者最大值一个一个的遍历出来。

选择排序法是将数组的第一个数据作为最大或者最小的值,然后通过比较循环,输出有序的数组。

插入排序是选择一个数组中的数据,通过不断的插入比较最后进行排序。

快速排序法、

原理:
选择数组中的一个元素作为标准,将所有比标准小的元素放到左边,所有比标准大的元素放到右边。 并对左边和右边的元素做一样的快速排序过程。
public int[] quickSort(int[]result) {
quick(result, 0, result.length- 1);
return result;
}


选择数组中的一个元素作为标准,将所有比标准小的元素放到左边,所有比标准大的元素放到右边并对左边和右边的元素做一样的快速排序过程。
private void quick(int[] array,int startIndex, int endIndex) {
int pIndex = startIndex;
for (int i = startIndex+ 1; i <= endIndex; i ++) {
if (array[i] < array[pIndex]) {
inttemp = array[i];
for(int j = i; j > pIndex; j --) {
array[j]= array[j - 1];
}
array[pIndex]= temp;
pIndex++;
}

}
if (pIndex - startIndex > 1) {
quick(array, startIndex,pIndex - 1);
}
if (endIndex - pIndex > 1) {
quick(array, pIndex+ 1, endIndex);
}
}

冒泡排序法

比较n轮,每一轮都把最大元素移动到数组后端。
public int[] bubbleSort(int[]result) {


for (int i = 0; i < ARRAYSIZE; i ++) {
for (int j = i + 1; j < ARRAYSIZE; j ++) {
if(result[i] > result[j]) {
swap(result,i, j);
}

}
}

return result;
}

选择排序法

每遍历未排序部分一次都选出一个最小值,并将最小值元素移动到数组前端
public int[] simpleSelectionSort(int[]result) {

int minIndex = 0;
for (int i = 0; i < result.length; i ++) {
minIndex = i;
for (int j = i + 1; j < result.length; j ++) {
if(result[j] < result[minIndex]) {
minIndex= j;
}

}
swap(result, minIndex,i);
}

return result;
}

private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

}

}

插入排序法

原理与插入排序类似,不同点在于寻找插入位置的时候,采取的是折半查找方法
public int[] binsertSort(int[] result) {

for (int i = 1; i < ARRAYSIZE; i ++) {
if (result[i] < result[0]) {
inttemp = result[i];
for(int j = i - 1; j >= 0; j --) {
result[j+ 1] = result[j];

}
result[0]= temp;

} else if (result[i] < result[i - 1]) {
intlarrange = 0;
intrarrange = i - 1;
while(rarrange - larrange > 1) {
intp = (rarrange + larrange + 1)/2;
if(result[i] < result[p]) {
rarrange= p;
}else {
larrange= p;
}

}
inttemp = result[i];
for(int j = i - 1; j >= larrange +1; j --) {
result[j+ 1] = result[j];

}
result[larrange+ 1] = temp;

}
}

return result;
}



  ------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------