工作2年多了吧,一直在换着工作,学习着不同的技术。重开始在学校学的JSP,到Android iOS COCOS2DX PHP。一直在换,我也不知道我喜欢干什么,也一直在思考我能做什么,我一直想我想要什么生活,我不知道。我也一直思考N年之久我还能记得计算机方面什么东西,我想想只有算法吧?新的工作做APP,1年多没做,很多新的知识学习。最后想想肯定坚持着什么,那就坚持算法学习了,关于算法,以前是我的强项,现在生疏,下午写了几个小代码。关于排序的,快速,归并,堆排序。直接贴代码。
package com.lsj.sort;
public class MergeSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[] = { 9, 4, 2, 3, 8, 5, 1, 3, 8, 7 };
sort(array, 0, 5, 9);
}
private static void sort(int[] array, int i, int j, int k) {
int n = j - i;
int m = k - j + 1;
if (n == m && n == 1) {
if (array[i] > array[j]) {
int t = array[i];
array[i] = array[j];
array[j] = t;
}
return;
}
if (n != 1)
sort(array, i, i + n / 2, j - 1);
if (m != 1)
sort(array, j, j + m / 2, k);
int a1[] = new int[n];
int a2[] = new int[m];
int clone[] = new int[n + m];
for (int pos = 0; pos < n; pos++) {
a1[pos] = array[i + pos];
}
for (int pos = 0; pos < m; pos++) {
a2[pos] = array[j + pos];
}
int pos1 = 0, pos2 = 0, pos = 0;
while (true) {
if (pos1 == n && pos2 == m)
break;
// System.out.println(pos1 + " " + pos2);
if (n != pos1 && (pos2 == m || a1[pos1] < a2[pos2])) {
clone[pos++] = a1[pos1++];
} else {
clone[pos++] = a2[pos2++];
}
}
System.out.println(i + " " + k);
for (pos = i; pos < k + 1; pos++) {
array[pos] = clone[pos - i];
System.out.print(array[pos] + " ");
}
System.out.println();
return;
}
}
package com.lsj.sort;
public class HeapSort {
public static void main(String[] args) {
int array[] = { 9, 4, 2, 3, 8, 5, 1, 3, 8, 7 };
sort(array, 10);
for (int i : array) {
System.out.print(i + " ");
}
}
private static void sort(int[] array, int length) {
buildingHeap(array, length);
for(int i = length - 1;i > 0 ; i --)
{
int temp = array[0];
array[0] = array[i];
array[i] = temp;
HeapAdjust(array, 0, i);
}
}
private static void buildingHeap(int[] array, int length) {
// TODO Auto-generated method stub
for (int i = (length -1) / 2 ; i >= 0; i--)
HeapAdjust(array,i,length);
}
private static void HeapAdjust(int array[],int s, int length)
{
int temp = array[s];
int child = s * 2 + 1;
while (child < length) {
if(child + 1 < length && array[child] < array[child + 1])
{
child++;
}
if(array[s] < array[child])
{
array[s] = array[child];
s = child;
child = 2 * child + 1;
}
else break;
array[s] = temp;
}
}
}
package com.lsj.sort;
public class QuickSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[] = { 5, 4, 2, 3, 8, 9, 1, 3, 8, 7 };
sort(array, 0, 9);
for (int i : array) {
System.out.print(i + " ");
}
}
private static void sort(int[] array, int n, int m) {
// System.out.println(" " + n + m);
int t = array[n];
int i = n;
int j = m;
while (i < j) {
// System.out.println(" " + i + j);
while (i < j && array[j] >= t)
j--;
array[i] = array[j];
while (i < j && array[i] <= t)
i++;
array[j] = array[i];
// i++;j--;
}
array[i] = t;
if (i - 1 > n)
sort(array, n, i - 1);
if (i + 1 < m)
sort(array, i + 1, m);
}
}