Oke, kali ini kita bertemu dalam permasalahan pemrograman. Kali ini saya akan sedikit membagikan hasil dari "Trial and Error" kelompok saya, hehe.
Oke, langsung saja ke permasalahannya ya, disini kita membuat pengurutan Quicksort yang inputan angkanya di import melalui random file yang dibuat dalam bentuk text file.
Untuk sourcecode-nya :
Monggo, untuk file text-nya silakan download disini
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.util.ArrayList;
- import java.util.Scanner;
- public class KwikSort {
- static int elements;
- static ArrayList<Integer> unsorted;
- static Scanner scanned;
- final static String NEWLINE = System.getProperty("line.separator");
- public static void main(String[] args) {
- initialize();
- loadToArray("c:\\random.txt");
- quickSort(0, elements-1);
- printList();
- }
- public static void initialize(){
- elements = 0;
- unsorted = new ArrayList<Integer>();
- }
- public static void loadToArray (String filepath){
- // filling ArrayList<Integer> called 'unsorted' with the numbers from inputfile
- try {
- scanned = new Scanner (new BufferedReader(new FileReader(filepath)));
- scanned.useDelimiter(NEWLINE);
- while (scanned.hasNext()) {
- elements++;
- unsorted.add(new Integer(scanned.next()));
- }
- } catch (FileNotFoundException e){System.out.println("File not Found");}
- }
- public static void quickSort (int first, int last){
- if (!(first < last)) { return; }
- int newPivotPosition = splitAroundPivot(first, last);
- quickSort (first, newPivotPosition - 1); //recursion to sort left of pivot
- quickSort (newPivotPosition + 1, last); //recursion to sort right of pivot
- }
- public static int splitAroundPivot (int firstInList, int lastInList){
- /* choose last element from the given range to be the pivot and
- * then sort all elements <= pivot on its left and >= pivot on its right
- * Once this is done, the new Pivot is set to the last element of the left-part of the list
- */
- int pivot = unsorted.get (lastInList);
- int first = firstInList;
- int last = lastInList -1;
- do{
- while ( unsorted.get(first) <= pivot && first < lastInList ) { first++; }
- while ( unsorted.get(last) >= pivot && last > firstInList ) { last--; }
- if (first < last) {
- // swap values because left is bigger than pivot and right smaller than pivot
- int temp = unsorted.get(first);
- unsorted.set(first, unsorted.get(last));
- unsorted.set(last, temp);
- }
- } while(first < last);
- if (unsorted.get(first) > pivot) {
- // swap pivot element with element at index 'first'
- int temp = unsorted.get(first);
- unsorted.set(first, unsorted.get(lastInList));
- unsorted.set(lastInList, temp);
- }
- return first; //first now represents the new pivot-position
- }
- public static void printList (){
- for (int i =0 ; i < elements; i++){
- System.out.println (unsorted.get(i));
- }
- }
- }
Monggo, untuk file text-nya silakan download disini
Tidak ada komentar:
Posting Komentar