Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.10 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Scanner;
  3.  
  4. ///////////////////////////////////////////
  5. //
  6. // Test frame for CS2 recitation assignments
  7. //   Created 12-10-2014 by Rick Leinecker
  8. //
  9. ///////////////////////////////////////////
  10.  
  11. public class CSRecitationWeek2
  12. {
  13.  
  14.     ///////////////////////////////////////////
  15.     //
  16.     // Start of assignment code.
  17.     //
  18.     ///////////////////////////////////////////
  19.  
  20.     /**
  21.      * Returns the last name, first name, and PID of the student.
  22.      *
  23.      * This is required in order to get credit for the programming assignment.
  24.      */
  25.     static String GetNameAndPID()
  26.     {
  27.         return( "Ashwas,Rubba,r3430968");
  28.     }
  29.    
  30.     static int[] DoBubbleSort( int[] DataIn )
  31.     {
  32.         //temp variable for storing the lesser element
  33.         int temp;
  34.         //first for-loop starts at second element
  35.         for(int i=1; i < DataIn.length; i++ )
  36.         {  
  37.         //second for-loop starts at first element
  38.             for(int j=0; j < DataIn.length-1; j++)
  39.             {
  40.                 //swap whenever the previous element is bigger than a following element
  41.                 if(DataIn[j] > DataIn[i])
  42.                 {
  43.                     temp = DataIn[i];
  44.                     DataIn[i] = DataIn[j];
  45.                     DataIn[j] = temp;
  46.                 }
  47.             }
  48.         }
  49.         //return sorted array
  50.         return DataIn;
  51.     }
  52.    
  53.         static int[] DoInsertSort( int[] DataIn )
  54.     {
  55.         //declare variables
  56.         int insert,j,i;
  57.         //start loop at second element
  58.         for( i=1; i < DataIn.length; i++)
  59.         {
  60.             //set the element at i to the variable insert (number to be inserted)
  61.             insert = DataIn[i];
  62.             //set j to i
  63.             j=i;
  64.             //loop until j=0 and while insert is less than the previous element
  65.             while(j>=1 && insert<DataIn[j-1])
  66.             {
  67.                 //move larger numbers down
  68.                 DataIn[j]=DataIn[j-1];
  69.                 //decrement
  70.                 j--;
  71.             }
  72.            
  73.             //insert value
  74.             DataIn[j] = insert;
  75.            
  76.         }
  77.        
  78.         //return sorted array
  79.         return DataIn;
  80.     }
  81.  
  82.         static int[] DoHeapSort( int[] DataIn )
  83.     {
  84.             heapSize = nHeap.length;
  85.            
  86.             nHeap = new int[heapSize];
  87.             nHeap = DataIn;
  88.            
  89.             BuildHeap();
  90.            
  91.             return DataIn;
  92.     }
  93.  
  94.     // The heap (min-heap).
  95.     static int[] nHeap;
  96.  
  97.     // Randomly generated numbers to be used as input.
  98.     static int[] nRandomNumbers;
  99.  
  100.     // The size of the heap, nHeap. The size of the heap may be smaller than
  101.     // nHeap.length. The heap is comprised of the elements at indexes between 0
  102.     // and heapSize-1 of nHeap.
  103.     static int heapSize;
  104.  
  105.     // Methods to get index of parent, left child, and right child of node at
  106.     // index nIndex of the heap  (zero-based index). The indexes outputed by
  107.     // GetLeft and GetRight must be verified to actually exist within the heap
  108.     // (use heapSize to determine this).
  109.  
  110.     private static int GetParentIndex(int nIndex)
  111.     {
  112.         int parent;
  113.         parent = (nIndex-1)/2;
  114.        
  115.         return parent;
  116.     }
  117.    
  118.     static int GetLeft( int nIndex )
  119.     {
  120.         int left;
  121.         left = nIndex*2 +1;
  122.        
  123.         return left;
  124.     }
  125.    
  126.     static int GetRight( int nIndex )
  127.     {
  128.         int right;
  129.         right = nIndex*2 + 2;
  130.        
  131.         return right;
  132.     }
  133.  
  134.     // Function to swap two numbers in an array. Auxiliary method to SiftUp and
  135.     // Heapify.
  136.         public static void swap(int arr[], int i, int j)
  137.         {
  138.             int temp;
  139.             temp = arr[i];
  140.             arr[i] = arr[j];
  141.             arr[j] = temp;
  142.        
  143.         }
  144.    
  145.     static void BuildHeap()
  146.     {
  147.         // Input: static field nHeap, an array of ints, representing a full
  148.         // binary tree (not a BST), except for the last level which may be
  149.         // only partially filled from the left
  150.  
  151.         // Input: static field heapSize
  152.  
  153.         // Output: modified nHeap such that it represents a min-heap  
  154.  
  155.         // Complexity: O(heapSize)
  156.  
  157.         // Start at the parent of the last node (i.e., the right-most,
  158.         // bottom-most node in the tree that is not a leaf)
  159.         //    - the last node is heapSize - 1
  160.         //    - the parent of any node is (nodeIdx - 1) / 2
  161.         //    - therefore the parent of the last node is
  162.         //      (heapSize - 2) / 2
  163.         //    - equivalent to GetParentIndex(heapSize-1)
  164.  
  165.         // Algorithm:
  166.  
  167.         // for i = GetParentIndex(heapSize-1) DOWN TO  0:
  168.         //      Heapify(i)
  169.        
  170.  
  171.         for( int i=GetParentIndex(heapSize-1); i>=0; i-- )
  172.         {
  173.             Heapify(i);
  174.         }
  175.        
  176.     }
  177.    
  178.    
  179.     static void Heapify( int nIndex )
  180.     {
  181.         // Input: static field nHeap, an array of ints, representing a full
  182.         // binary tree (not a BST), except for the last level which may be
  183.         // only partially filled from the left
  184.        
  185.         // Input: nIndex, an index into nHeap
  186.        
  187.         // Output: modified nHeap such that element nIndex has been "sifted
  188.         // down" until that element is less than its children or that element
  189.         // is a leaf
  190.  
  191.         // Another name for this method might be "SiftDown".
  192.  
  193.         // Algorithm:
  194.        
  195.          
  196.         // If nIndex is a leaf node (has no children), then there is nothing to
  197.         // do (use heapSize to determine this)
  198.          if(heapSize==1)
  199.              return;
  200.          
  201.         int smallest=nIndex;
  202.         int leftIdx = GetLeft(nIndex);
  203.         int rightIdx = GetRight(nIndex);
  204.  
  205.         if(nHeap[leftIdx] < nHeap[nIndex])
  206.             smallest = leftIdx;
  207.         if(nHeap[rightIdx] < nHeap[nIndex])
  208.             smallest = rightIdx;
  209.        
  210.         // smallest <- either the index leftIdx, rightIdx, or nIndex whose
  211.         // corresponding heap node value is the smallest out of these three
  212.         // (however, ensure that leftIdx and rightIdx are actually children;
  213.         // use heapSize to determine this)
  214.        
  215.         if(smallest != nHeap[nIndex])
  216.         {
  217.             swap(nHeap, smallest, nIndex);
  218.             Heapify(smallest);
  219.         }
  220.            
  221.         // if smallest != nIndex:
  222.         //    COMMENT: This means the node at nIndex has a child smaller than
  223.         //    itself at index smallest. This smallest child needs to come up
  224.         //    and replace the node at nIndex, and the node at nIndex needs to
  225.         //    come down to replace the smallest child. We then repeat the
  226.         //    process recursively at index smallest.
  227.  
  228.         //    swap node values at indexes smallest and nIndex
  229.        
  230.     }
  231.  
  232.  
  233.     // The following methods, AddElement and its auxiliary method SiftUp, are
  234.     // not used with DoHeapSort.
  235.  
  236.     // DoHeapSort uses BuildHeap instead, which is a more efficient way (O(n))
  237.     // to build a heap starting from a list of numbers than AddElement. The way
  238.     // to build a heap using AddElement is to start with an empty heap and
  239.     // repeatedly add each element into the heap. This way is O(nlogn).
  240.     // However, AddElement is useful to add new elements into an existing heap
  241.     // once it has been built with BuildHeap.
  242.  
  243.     static void AddElement( int nNumber )
  244.     {
  245.         // Input: static fields nHeap, heapSize. nHeap must already be a valid
  246.         // min-heap.
  247.  
  248.         // Input: nNumber, a new node to add to the heap
  249.        
  250.         // Output: heap with nNumber added, heapSize increased by 1
  251.  
  252.         // Complexity: O(log(heapSize))
  253.         if(heapSize+1 > nHeap.length)
  254.         {
  255.               int[] doubleArray;
  256.               doubleArray = new int[2*(nHeap.length)];
  257.               for(int i=0; i<nHeap.length; i++)
  258.                   doubleArray[i]=nHeap[i];
  259.              
  260.  
  261.             heapSize++;
  262.             doubleArray[heapSize-1]=nNumber;
  263.             SiftUp(heapSize-1);
  264.            
  265.         }
  266.    
  267.         else {
  268.         heapSize++;
  269.         nHeap[heapSize-1]=nNumber;
  270.         SiftUp(heapSize-1);
  271.              }
  272.            
  273.         // Precondition: heapSize+1 <= nHeap.length
  274.         // If this is not the case, before running the algorithm, create a new
  275.         // array that is double the size of nHeap, copy the elements of nHeap
  276.         // into it, and assign nHeap to be the new larger array
  277.  
  278.         // Algorithm:
  279.  
  280.         // Increase heapSize by 1
  281.         // Copy nNumber to index heapSize-1 of the heap
  282.         // SiftUp(heapSize-1)
  283.     }
  284.    
  285.     static void SiftUp( int nNodeIndex )
  286.     {
  287.         // repeatedly sift up the element at nNodeIndex as long as its parent
  288.         // node is greater or the element is the root (this is similar to
  289.         // Heapify but it moves the element upwards instead of downwards)
  290.        
  291.         int index, temp;
  292.         if( nNodeIndex != 0 )
  293.         {
  294.             // Get the parent index so that we can
  295.             index = GetParentIndex( nNodeIndex );
  296.  
  297.             //compare parent with the number at the specified index
  298.             if( nHeap[index] > nHeap[nNodeIndex] )
  299.             {
  300.                 // Swap the parent and child.
  301.                 temp = nHeap[index];
  302.                 nHeap[index] = nHeap[index];
  303.                 nHeap[nNodeIndex] = temp;
  304.  
  305.                 // recursively call to sort
  306.                 SiftUp(index);
  307.             }
  308.         }
  309.        
  310.     }
  311.  
  312.     ///////////////////////////////////////////
  313.     //
  314.     // End of assignment code.
  315.     //
  316.     ///////////////////////////////////////////
  317.  
  318.     public static void setRandomArray(int n)
  319.     {
  320.         Random rnd = new Random();
  321.         nRandomNumbers = new int[n];
  322.         for( int i=0; i<nRandomNumbers.length; i++ )
  323.         {
  324.             nRandomNumbers[i] = rnd.nextInt( 500 );
  325.         }
  326.     }
  327.    
  328.     public static void main(String[] args)
  329.     {
  330.             System.out.println();
  331.         System.out.println();
  332.        
  333.         int[] array = {1,5,2,1,4,6};
  334.         DoBubbleSort(array);
  335.         System.out.println("BubbleSort:");
  336.         for(int y=0; y<array.length; y++)
  337.             System.out.printf("%d ",array[y]);
  338.        
  339.         System.out.println();
  340.         System.out.println();
  341.        
  342.         int[] array2 = {1,5,2,10,4,6,5,2,10,3,5,6};
  343.         DoInsertSort(array2);
  344.         System.out.println("InsertSort:");
  345.         for(int y=0; y<array2.length; y++)
  346.             System.out.printf("%d ",array2[y]);
  347.        
  348.        System.out.println();
  349.        System.out.println();
  350.  
  351.  
  352.        
  353.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement