高级农民
- 积分
- 1032
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-12-13
- 最后登录
- 1970-1-1
|
5/10 慢悠悠做了 Selection Sort and Merge Sort 看到大神们一天刷8道 好羡慕
不明白Merge Sort 有个地方用while为什么会越界 代码在最下面 求大神指教~~
Selection Sort
public class Solution {
public int[] solve(int[] array) {
// Write your solution here
if (array == null || array.length == 0){
return array;
}
for(int i = 0; i <array.length - 1; i++){
for (int j = i + 1; j < array.length; j++){
if (array[i] > array[j]){
swap(array, i, j);
}
}
}
return array;
}
private void swap(int[] array, int left, int right){
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
time complexity 1 + 2 +3+..+ n - 1 =n^2 o(n^2)
space comlexity o(1)
Merge Sort
public class Solution {
public int[] mergeSort(int[] array) {
// Write your solution here
if (array == null || array.length == 0){ //array.length没有括号
return array;
}
int[] helper = new int[array.length];//这里不用加括号
mergeSort(array, helper, 0, array.length - 1);
return array;
}
private void mergeSort(int[] array, int[] helper, int left, int right){
if(left >= right){
return;
}
int mid = left + (right - left)/2; //防止overflow
mergeSort(array, helper, left, mid);
mergeSort(array, helper, mid + 1, right);
merge(array, helper, left, mid, right); //左边,分界线,右边
}
private void merge(int[] array, int[] helper, int left, int mid, int right){
int lIndex = left;
int rIndex = mid + 1; //mid + 1 是右半边的最多端
int Index = left;
// while(Index <= right){
// helper[Index++] = array[Index++];//先赋值再加减
//} 不明白为什么这里会报错 越界了array 改成了for循环就好了 求大神指导一下
for (int i = left; i <= right; i++){
helper[i] = array[i];
}
while(lIndex <= mid && rIndex <= right){
if (helper[lIndex] <= helper[rIndex]){
array[left++] = helper[lIndex++];
}else{
array[left++] = helper[rIndex++];
}
}
while (lIndex <= mid){
array[left++] = helper[lIndex++]; //如果左半边有剩余 也要复制上去, 右半边不用管
}
}
}
|
|