Sunteți pe pagina 1din 3

/*

* To change this template, choose Tools | Templates


* and open the template in the editor.
*/
package alpro;

import java.util.Scanner;

/**
*
* @author LENOVO
*/
public class mager {
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.

/**
*
* @author LENOVO
*/

int n;
int[] num;
boolean run=true;
String pilih;

void getNumbers(){

Scanner melbu = new Scanner(System.in);

System.out.println("\tMerge Sort");
System.out.println("___________________________________________");
System.out.println("\nKlik enter 'n' masukkan nilai :");
n = Integer.parseInt(melbu.nextLine());

System.out.println("Masukkan angka:");
num = new int[n];

for(int i=0; i<n; i++) {

num[i] = Integer.parseInt(melbu.nextLine());
}

System.out.println("\nSebelum disortir");

for(int i=0; i<n; i++) {

System.out.print(" " + num[i]);


}

MergeSort(num, 0, n-1);

System.out.println("\n\nSetelah disortir");

System.out.println("\nAscending Output");
for(int i=0; i<n; i++) {

System.out.print(" " + num[i]);


}

System.out.println("\nDescending Output");

for(int i=n-1; i>=0; i--) {

System.out.print(" " + num[i]);


}

private static void MergeSort(int[] num, int i, int j) {

int low = i;
int high = j;

if (low >= high) {

return;
}

int middle = (low + high) / 2;

int end_low = middle;


int start_high = middle + 1;

while ((low <= end_low) && (start_high <= high)) {

if (num[low] < num[start_high]) {

low++;
}
else {

int Temp = num[start_high];

for (int k = start_high- 1; k >= low; k--) {

num[k+1] = num[k];
}

num[low] = Temp;
low ++;
end_low ++;
start_high ++;
}

MergeSort(num, low, middle);


MergeSort(num, middle + 1, high);}

public static void main(String args[]) {


//perulangannya disini yaa
boolean run = true;
String jawab;
Scanner in= new Scanner(System.in);
while (run)
{

mager obj = new mager ();

obj.getNumbers();

System.out.print("\n\tApakah anda ingin mengurutkan angka lagi


(y/n) ? ");
jawab = in.next();
if (jawab.equalsIgnoreCase("y"))
{
run=true;
}
else
run = false;
}
}

S-ar putea să vă placă și