Pages

Saturday, 13 February 2016

Program Bubble Sort dan Insert Sort || Pemograman Java

Buat program untuk mengurutkan data dengan metode:
a. Bubble sort
   P E N Y E L E S A I A N : 
   package mengurutkandata;
import java.util.*; //BUBBLE SORT
public class Main {

public static void main(String[] args) {
 // instansiasi variabel scanner
 Scanner i = new Scanner(System.in);

int[] angka = new int[10];
for(int a = 0; a <= 9; a++){
      System.out.print("Masukan angka ke-"+(a+1)+" : ");
      angka[a] = i.nextInt();
}

for (int x = 0; x <= 8; x++) {
      for (int y = x+1; y<= 9; y++) {
                  if(angka[x] > angka[y]){
                              int temp = angka[x];
                              angka[x] = angka[y];
                              angka[y] = temp;
                  }
                        }
}

for (int t = 0;t < angka.length ; t++ ) {
      System.out.println("Angka ke-"+(t+1)+" : "+angka[t]);
}
    }
}  H A S I L : 

b.     Insert Sort
P E N Y E L E S A I A N :
                   package mengurutkandatainsertsort;
                   import java.util.*; //INSERT SORT
                   public class Main {
                   public static void main(String[] args) {
                   Scanner scan = new Scanner (System.in);
                   System.out.print("Masukan jumlah angka = ");
                   int angka = scan.nextInt();
                   int arr[]= new int [angka];
                   for (int x = 0; x < angka;x++){
                    System.out.print("Masukan angka ke "+(x+1)+" = ");
                   arr[x]=scan.nextInt();
                   }
                   System.out.println("Hasil angka setelah sort Descending : ");
                   insertionSort(arr, arr.length);

                   for(int r = 0; r < arr.length; r++) {
                   System.out.print(arr[r] + " ");
                   }
                   }
                   static int[] insertionSort(int array[], int n) {
                   for (int r = 1; r<n; r++)
                   {
                   int j = r;
                   int b = array[r];
                   while ((j > 0) && (array[j-1]< b ))
                   {
                        array[j] = array[j-1];
                         j--;
                   }
                        array[j]= b;
                   }
                        return array;
                   }
            }

     P E N Y E L E S A I A N : 


0 komentar:

Post a Comment