/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sorting;
/**
*
* @author Masiti
*/
public class merge {
static int swap;
static int cari;
public static void main(String[] args) {
int i;
int array[] = {20, 29, 7, 3, 31, 2, 5, 11, 9, 17};
System.out.print("nilai sebelum:\n");
for (i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
mergeSort_srt(array,array.length);
System.out.print("setelah sorting:\n");
for (i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
int temp = 0;
int n = array.length;
int count = 0;
for (int a = 0; a < n; a++) {
for (int j = 1; j < (n - a); j++) {
if (array[j - 1] > array[j]) {
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
count++;
}
}
}
System.out.println();
System.out.println("Data sorted after " + swap + " times swapping");
System.out.println("Data sorted after " + cari + " searching");
}
public static int mergeSort_srt(int a[], int n) {
int search = 0;
int temp = 0, count = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
count++;
swap = count;
}
else{
search++;
cari = search;
}
}
}
return count;
}
public static void mergeSort_srt(
int array[], int lo, int n) {
int low = lo;
int high = n;
if (low >= high) {
return;
}
int middle = (low + high) / 2;
mergeSort_srt(array, low, middle);
mergeSort_srt(array, middle + 1, high);
int end_low = middle;
int start_high = middle + 1;
while ((lo <= end_low) && (start_high <= high)) {
if (array[low] < array[start_high]) {
low++;
} else {
int Temp = array[start_high];
for (int k = start_high - 1; k >= low; k--) {
array[k + 1] = array[k];
}
array[low] = Temp;
low++;
end_low++;
start_high++;
}
}
}
}
Tidak ada komentar:
Posting Komentar