To tackle the sorting problem, I decided to write a simple merge-sort program. Basically, a merge-sort takes a list of elements, splits it in two, then recursively splits each of those lists into two, and so on until all that remains are a number of lists with only 2 elements in them. After sorting those lists, the sort then reverses its splitting process by merging lists together, to create the sorted whole.
/*
A Simple Merge Sort
Gabriel Kishi
9/7/2010
*/
import java.util.Random;
public class mergeSortingHat
{
public static void main(String[] args)
{
// seeds the random number generator
Random r = new Random(System.currentTimeMillis());
// creates an array of 100 random numbers between 0 and 10000
// Note: I tested this up to 10000 numbers between -2,147,483,648 to +2,147,483,647
// which, while it computed rather quickly, crashed my IDE while it was printing!
int[] a = new int[100];
for (int x = 0; x < a.length; x++)
{
a[x] = r.nextInt(1000);
}
// prints the initial array
for (int y: a)
{
System.out.print(y + " ");
}
System.out.println("\n");
//prints the sorted array
for (int y: mergeSort(a))
{
System.out.print(y + " ");
}
}
public static int[] mergeSort(int[] arr)
{
if (arr.length < 2)
{
// if array contains 1 or 0 elements, no need to sort it
return arr;
}
if (arr.length == 2)
{
// sorts an array w/ 2 elements
if (arr[0] > arr[1])
{
int temp = arr[0];
arr[0] = arr[1];
arr[1] = arr[0];
return arr;
}
}
//if array has more than two elements, splits the array into two parts
//and then calls mergeSort recursively to sort the arrays, and finally
//merges the two arrays
int split = arr.length/2;
int[] arr1 = new int[split];
int[] arr2 = new int[arr.length-split];
for (int x = 0; x < arr.length; x++)
{
if (x < split)
arr1[x] = arr[x];
else
arr2[x-split] = arr[x];
}
return merge(mergeSort(arr1), mergeSort(arr2));
}
public static int[] merge (int[] arr1, int[] arr2)
{
//merges two arrays
int len1 = 0;
int len2 = 0;
int[] newArr = new int[arr1.length + arr2.length];
for (int x = 0; x < newArr.length; x++)
{
if (len1 == arr1.length && len2 < arr2.length)
{
newArr[x] = arr2[len2];
len2++;
}
else if (len2 == arr2.length && len1 < arr1.length)
{
newArr[x] = arr1[len1];
len1++;
}
else if (arr1[len1] < arr2[len2])
{
newArr[x] = arr1[len1];
len1++;
}
else
{
newArr[x] = arr2[len2];
len2++;
}
}
return newArr;
}
}
Edit: Allowed comments; Sorry about that!
ReplyDelete