Created
November 2, 2012 08:42
-
-
Save meklu/3999535 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.meklu.noobtils; | |
import org.meklu.noobtils.Read; | |
public class ascensionenhanced { | |
private static Read read = new Read(); | |
/** | |
* @author Melker "meklu" Narikka | |
*/ | |
// a method for sorting some amount of integers provided by the user | |
public static void main(String[] args) { | |
String Prompt = "How many values will be put in the array? ", | |
Errprompt = "Check your input and try again: "; | |
int arrlength; | |
boolean hasfailed = false; | |
do { | |
if (hasfailed) System.out.println("You can't have a negative amount of items, silly fellow."); | |
arrlength = read.Int(Prompt, Errprompt); | |
hasfailed = true; | |
} while (arrlength < 0); | |
if (arrlength == 0) { System.out.println(":C"); return; } | |
// the number of elements in nums[] determines the amount of numbers asked | |
int[] nums = new int[arrlength]; | |
for (int i = 0; i < nums.length; i += 1) { | |
nums[i] = read.Int("Enter number #" + (i + 1) + ": ", "Please enter a proper integer: "); | |
} | |
// bubblesort is quite easy to implement, so why not | |
boolean haschanged; | |
int pass = 0; | |
int swapcount = 0; | |
int length = nums.length; | |
long t_diff = 0; | |
long t_end = 0; | |
long t_start = System.nanoTime(); | |
do { | |
haschanged = false; | |
// using nums[n - 1] since we're comparing n and n + 1 anyway | |
for (int i = 0; i < length - 1; i += 1) { | |
int buf; | |
if (nums[i] > nums[i + 1]) { | |
buf = nums[i + 1]; | |
nums[i + 1] = nums[i]; | |
nums[i] = buf; | |
swapcount += 1; | |
haschanged = true; | |
} | |
} | |
length -= 1; | |
pass += 1; | |
} while (haschanged); | |
t_end = System.nanoTime(); | |
t_diff = t_end - t_start; | |
String output = ""; | |
for (int i = 0; i < nums.length; i += 1) { | |
if (i == nums.length - 2) { | |
output = output.concat(nums[i] + " and "); | |
} else if (i != nums.length - 1) { | |
output = output.concat(nums[i] + ", "); | |
} else { | |
output = output.concat(Integer.toString(nums[i])); | |
} | |
} | |
System.out.println("The numbers in ascending order are " + output + "."); | |
System.out.println("The Bubblesort implementation took " + t_diff + " nanoseconds and used " + pass + " passes and " + swapcount + " swaps."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment