Algoritma Sorting : Bubble Sort menggunakan Java

Bubble Sort : algoritma sorting sederhana yang bekerja dengan berulang kali melangkah melalui daftar yang akan diurutkan, membandingkan setiap pasangan item yang berdekatan dan swapping  jika mereka berada di urutan yang salah.
Berikut ini adalah Script Code untuk Algoritma Sorting Bubble Sorting menggunakan Java
import java.util.Arrays;
/**
* @author Crunchify.com.
* How to Implement Bubble sort algorithm in Java? Ascending and Descending Order Tutorial
*/
public class CrunchifyBubbleSort {
public static void main(String[] args) {
int crunchifyArry[] = { 15, 3, 9, 7, 19, 8, 1, 5 };
log(“Let’s get started on Bubble Sort implementation in Java \n”);
log(“============ Ascending Order result:” + Arrays.toString(CrunchifyBubbleSortAsceMethod(crunchifyArry)) + “\n”);
log(“============ Descending Order result:” + Arrays.toString(CrunchifyBubbleSortDescMethod(crunchifyArry)) + “\n”);
}
// Bubble Sort Algorithm in Ascending Order
public static int[] CrunchifyBubbleSortAsceMethod(int[] crunchifyArr) {
int temp;
for (int i = 0; i < crunchifyArr.length 1; i++) {
for (int j = 1; j < crunchifyArr.length i; j++) {
if (crunchifyArr[j 1] > crunchifyArr[j]) {
temp = crunchifyArr[j 1];
crunchifyArr[j 1] = crunchifyArr[j];
crunchifyArr[j] = temp;
}
}
log(“Iteration “ + (i + 1) + “: “ + Arrays.toString(crunchifyArr));
}
return crunchifyArr;
}
// Bubble Sort Algorithm in Descending Order
public static int[] CrunchifyBubbleSortDescMethod(int[] crunchifyArr) {
int temp;
for (int i = 0; i < crunchifyArr.length 1; i++) {
for (int j = 1; j < crunchifyArr.length i; j++) {
if (crunchifyArr[j 1] < crunchifyArr[j]) {
temp = crunchifyArr[j 1];
crunchifyArr[j 1] = crunchifyArr[j];
crunchifyArr[j] = temp;
}
}
log(“Iteration “ + (i + 1) + “: “ + Arrays.toString(crunchifyArr));
}
return crunchifyArr;
}
// Simple log util
private static void log(String result) {
System.out.println(result);
}
}
Sumber : crunchify
Advertisements

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