Home > JAVA > Pengurutan di Java

Pengurutan di Java

Buble Sort


public class TryBubleShort {

 public static void main(String[] args) {
  int[] intArray = new int[]{34,40,12,5,7,2012,4};
  int[] intArrayShortAsc = bubleShortAsc(intArray);
  System.out.println("Data awalnya " + Arrays.toString(intArray));
  System.out.println("Diurut ascending " + Arrays.toString(intArrayShortAsc));
 }
 public static int[] bubleShortAsc(int[] arr){
  int panjangArray = arr.length;
  int temp = 0;
  for(int i=0; i<panjangArray; i++){
   for(int j=1; j<(panjangArray-1); j++){
    if(arr[j-1]<arr[j]){
     temp = arr[j-1];
     arr[j-1] = arr[j];
     arr[j] = temp;
    }
   }
 }
 return arr;
 }
 public static int[] bubleShortDesc(int[] arr){
  int panjangArray = arr.length;
  int temp = 0;
  for(int i=0; i<panjangArray; i++){
   for(int j=1; j<(panjangArray-1); j++){
    if(arr[j-1]>arr[j]){
     temp = arr[j-1];
     arr[j-1] = arr[j];
     arr[j] = temp;
    }
   }
  }
  return arr;
 }
}

Quick Sort


public class TryQuickSort {
 private static int[] intArray = new int[]{34,40,12,5,7,2012,4};
 public static void main(String[] args) {
  System.out.println("Sebelum diurutkan " + Arrays.toString(intArray));
  quickSort(0, intArray.length-1);
  System.out.println("Setelah diurutkan " + Arrays.toString(intArray));
 }
 private static void quickSort(int low, int high){
  int i=low;
  int j=high;
  int pivot = intArray[low+(high-low)/2];
  while(i<=j){
   while(intArray[i] < pivot){
    i++;
   }
   while(intArray[j] > pivot){
    j--;
   }
   if(i<=j){
    tukar(i,j);
    i++;
    j--;
   }
  }
  if(low < j)
   quickSort(low, j);
  if(i < high)
   quickSort(i, high);
 }
 private static void tukar(int i, int j){
  int temp = intArray[i];
  intArray[i] = intArray[j];
  intArray[j] = temp;
 }
}

Categories: JAVA
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: