Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SortTest{
- public static void main(String args[]){
- int theArray[] = {4,2,5,1,3,18,0,9,6};
- //selectionSort(theArray);
- //insertionSort(theArray);
- mergeSort(theArray, 0, theArray.length - 1);
- for(int j = 0; j < theArray.length; j++){
- System.out.print(theArray[j] + " ");
- }
- System.out.println(" ");
- }
- public static void selectionSort(int a[ ]){
- int minIndex, min;
- for(int i = 0; i < a.length - 1; i++){//keeps track of swap position
- minIndex = i;
- min = a[i];
- for(int j = i + 1; j < a.length; j++){//finds the minIndex
- if(a[j] < min){
- minIndex = j;
- min = a[j];
- }
- }
- //swap after finding min
- int temp = a[i];
- a[i] = a[minIndex];
- a[minIndex] = temp;
- }
- }
- public static void insertionSort(int a[ ]){
- int itemToInsert, j;
- boolean keepGoing;
- //On kth pass, insert item k into its correct position
- //among the first k elements in the array
- for(int k = 1; k < a.length; k++){
- //Go backwards through the sorted part of the array
- //looking for the correct spot for the kth element
- itemToInsert = a[k];
- j = k - 1;
- keepGoing = true;
- while( j >= 0 && keepGoing == true ){
- if(itemToInsert < a[j]){
- //If element is less than a[j], shift to the right to make room
- a[j+1] = a[j];
- j--;
- if( j == -1 ){//If we are at the leftmost element, insert
- a[0] = itemToInsert;
- }
- }
- else{//The correct place for the element is found, insert
- keepGoing = false;
- a[j+1] = itemToInsert;
- }
- }
- }
- }
- //This does the initial splitting step
- public static void mergeSort(int a[ ], int left, int right){
- if(right == left) return;
- int middle = (left + right) / 2;
- mergeSort(a, left, middle);//recursion (left half)
- mergeSort(a, middle + 1, right);//recursion (right half)
- merge(a, left, middle, right);//seen soon
- }
- //This does the final step of merging
- public static void merge(int a[], int left, int middle, int right){
- //Temporary array to build the merged list
- int tempArr[] = new int[right - left + 1];
- int index1 = left;
- int index2 = middle + 1;
- int indx = 0;
- //Loop until one of the sublists is finished, adding the smaller
- //of the first elements of each sublist to the merged list
- while(index1 <= middle && index2 <= right){
- if(a[index1] < a[index2]){
- tempArr[indx] = a[index1];
- index1++;
- }
- else{
- tempArr[indx] = a[index2];
- index2++;
- }
- indx++;
- }
- //Add to the merged "list" the remaining elements of whichever
- //"sublist" is not yet finished
- while( index1 <= middle ){
- tempArr[indx] = a[index1];
- index1++;
- indx++;
- }
- while( index2 <= right){
- tempArr[indx] = a[index2];
- index2++;
- indx++;
- }
- //Copy the merged list from the tempArr into the a array
- for( indx = 0; indx < tempArr.length; indx++ ){
- a[left + indx ] = tempArr[indx];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement