Created
October 3, 2013 13:06
-
-
Save tommy351/6809517 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
import java.util.*; | |
public class s401631741HW1 { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
System.out.print("i = "); | |
int number = scanner.nextInt(); | |
Random random = new Random(); | |
int[][] arr = new int[number][]; | |
for (int i = 0; i < number; i++) { | |
arr[i] = generateString(random.nextInt(30) + 1); | |
} | |
System.out.print("\nOriginal:\n"); | |
for (int[] str : arr) { | |
printString(str); | |
} | |
System.out.print("\nSorted:\n"); | |
for (int[] str : arr) { | |
printString(sortString(str)); | |
} | |
} | |
private static int[] generateString(int length) { | |
int[] str = new int[length]; | |
Random random = new Random(); | |
for (int i = 0; i < length; i++) { | |
str[i] = random.nextInt(26) + 97; | |
} | |
return str; | |
} | |
private static int[] sortString(int[] str) { | |
return quickSort(str, 0, str.length - 1); | |
} | |
private static void printString(int[] str) { | |
for (int i = 0; i < str.length; i++) { | |
System.out.print((char) str[i]); | |
} | |
System.out.println(); | |
} | |
private static int[] quickSort(int[] arr, int left, int right) { | |
if (right <= left) return arr; | |
int pivotIndex = (left + right) / 2; | |
int pivot = arr[pivotIndex]; | |
swap(arr, pivotIndex, right); | |
int swapIndex = left; | |
for (int i = left; i < right; i++) { | |
if (arr[i] <= pivot) { | |
swap(arr, i, swapIndex++); | |
} | |
} | |
swap(arr, swapIndex, right); | |
quickSort(arr, left, swapIndex - 1); | |
quickSort(arr, swapIndex + 1, right); | |
return arr; | |
} | |
private static void swap(int[] arr, int a, int b) { | |
int tmp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = tmp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment