/*
稳定性:[稳定](不稳定的算法结构:如果有两个相同的元素5,会导致第一个5和第二个5的位置发生改变)
*/
package seven_happy;
public class Code_Demo {
/**
* author: Ain
* model: write a code about MergeSort
* date:2016-3-9
*/
// 定义变量值
private static final int[] a = { 9, 5, 7, 10, 6, 8 };
private static final String SORT_AGO = "归并排序之前:";
private static final String SORT_AFTER ="归并排序之后:";
// 主程序入口
public static void main(String[] args) {
int[] a={0, 3 ,1 ,8 ,7 ,2 ,5 ,4 ,6 ,9};
System.out.print(SORT_AGO);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
//归并排序
mergeSort(a,0,a.length-1);
System.out.println(" ");
System.out.print(SORT_AFTER);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
private static void mergeSort(int[] a, int left, int right) {
if(left<right){
int middle = (left+right)/2;
//对左边进行递归
mergeSort(a, left, middle);
//对右边进行递归
mergeSort(a, middle+1, right);
//合并
merge(a,left,middle,right);
}
}
private static void merge(int[] a, int left, int middle, int right) {
int[] tmpArr = new int[a.length];
int mid = middle+1; //右边的起始位置
int tmp = left;
int third = left;
while(left<=middle && mid<=right){
//从两个数组中选取较小的数放入中间数组
if(a[left]<=a[mid]){
tmpArr[third++] = a[left++];
}else{
tmpArr[third++] = a[mid++];
}
}
//将剩余的部分放入中间数组
while(left<=middle){
tmpArr[third++] = a[left++];
}
while(mid<=right){
tmpArr[third++] = a[mid++];
}
//将中间数组复制回原数组
while(tmp<=right){
a[tmp] = tmpArr[tmp++];
}
}
}
稳定性:[稳定](不稳定的算法结构:如果有两个相同的元素5,会导致第一个5和第二个5的位置发生改变)
*/
package seven_happy;
public class Code_Demo {
/**
* author: Ain
* model: write a code about MergeSort
* date:2016-3-9
*/
// 定义变量值
private static final int[] a = { 9, 5, 7, 10, 6, 8 };
private static final String SORT_AGO = "归并排序之前:";
private static final String SORT_AFTER ="归并排序之后:";
// 主程序入口
public static void main(String[] args) {
int[] a={0, 3 ,1 ,8 ,7 ,2 ,5 ,4 ,6 ,9};
System.out.print(SORT_AGO);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
//归并排序
mergeSort(a,0,a.length-1);
System.out.println(" ");
System.out.print(SORT_AFTER);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
private static void mergeSort(int[] a, int left, int right) {
if(left<right){
int middle = (left+right)/2;
//对左边进行递归
mergeSort(a, left, middle);
//对右边进行递归
mergeSort(a, middle+1, right);
//合并
merge(a,left,middle,right);
}
}
private static void merge(int[] a, int left, int middle, int right) {
int[] tmpArr = new int[a.length];
int mid = middle+1; //右边的起始位置
int tmp = left;
int third = left;
while(left<=middle && mid<=right){
//从两个数组中选取较小的数放入中间数组
if(a[left]<=a[mid]){
tmpArr[third++] = a[left++];
}else{
tmpArr[third++] = a[mid++];
}
}
//将剩余的部分放入中间数组
while(left<=middle){
tmpArr[third++] = a[left++];
}
while(mid<=right){
tmpArr[third++] = a[mid++];
}
//将中间数组复制回原数组
while(tmp<=right){
a[tmp] = tmpArr[tmp++];
}
}
}