Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.91 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.            
  85.         return DataIn;
  86.     }
  87.  
  88.     // The heap (min-heap).
  89.     static int[] nHeap;
  90.  
  91.     // Randomly generated numbers to be used as input.
  92.     static int[] nRandomNumbers;
  93.  
  94.     // The size of the heap, nHeap. The size of the heap may be smaller than
  95.     // nHeap.length. The heap is comprised of the elements at indexes between 0
  96.     // and heapSize-1 of nHeap.
  97.     static int heapSize;
  98.  
  99.     // Methods to get index of parent, left child, and right child of node at
  100.     // index nIndex of the heap  (zero-based index). The indexes outputed by
  101.     // GetLeft and GetRight must be verified to actually exist within the heap
  102.     // (use heapSize to determine this).
  103.  
  104.     private static int GetParentIndex(int nIndex)
  105.     {
  106.         int parent;
  107.         parent = nIndex/2;
  108.        
  109.         return parent;
  110.     }
  111.  
  112.     static int GetLeft( int nIndex )
  113.     {
  114.         int left;
  115.         left = nIndex*2;
  116.        
  117.         return left;
  118.     }
  119.    
  120.     static int GetRight( int nIndex )
  121.     {
  122.         int right;
  123.         right = nIndex*2 + 1;
  124.        
  125.         return right;
  126.     }
  127.  
  128.     // Function to swap two numbers in an array. Auxiliary method to SiftUp and
  129.     // Heapify.
  130.         public static void swap(int arr[], int i, int j)
  131.         {
  132.             int temp;
  133.             temp = arr[i];
  134.             arr[i] = arr[j];
  135.             arr[j] = temp;
  136.         }
  137.    
  138.     static void BuildHeap()
  139.     {
  140.         // Input: static field nHeap, an array of ints, representing a full
  141.         // binary tree (not a BST), except for the last level which may be
  142.         // only partially filled from the left
  143.  
  144.         // Input: static field heapSize
  145.  
  146.         // Output: modified nHeap such that it represents a min-heap  
  147.  
  148.         // Complexity: O(heapSize)
  149.  
  150.         // Start at the parent of the last node (i.e., the right-most,
  151.         // bottom-most node in the tree that is not a leaf)
  152.         //    - the last node is heapSize - 1
  153.         //    - the parent of any node is (nodeIdx - 1) / 2
  154.         //    - therefore the parent of the last node is
  155.         //      (heapSize - 2) / 2
  156.         //    - equivalent to GetParentIndex(heapSize-1)
  157.  
  158.         // Algorithm:
  159.  
  160.         // for i = GetParentIndex(heapSize-1) DOWN TO  0:
  161.         //      Heapify(i)
  162.        
  163.         nHeap = new int[nRandomNumbers.length];
  164.         for( int i=0; i<nRandomNumbers.length; i++ )
  165.         {
  166.             AddElement(i);
  167.         }
  168.        
  169.     }
  170.    
  171.    
  172.     static void Heapify( int nIndex )
  173.     {
  174.         // Input: static field nHeap, an array of ints, representing a full
  175.         // binary tree (not a BST), except for the last level which may be
  176.         // only partially filled from the left
  177.        
  178.         // Input: nIndex, an index into nHeap
  179.        
  180.         // Output: modified nHeap such that element nIndex has been "sifted
  181.         // down" until that element is less than its children or that element
  182.         // is a leaf
  183.  
  184.         // Another name for this method might be "SiftDown".
  185.  
  186.         // Algorithm:
  187.        
  188.          
  189.         // If nIndex is a leaf node (has no children), then there is nothing to
  190.         // do (use heapSize to determine this)
  191.          if(heapSize==1)
  192.              return;
  193.          
  194.         int smallest=nHeap[nIndex];
  195.         int leftIdx = GetLeft(nIndex);
  196.         int rightIdx = GetRight(nIndex);
  197.  
  198.         if(nHeap[leftIdx] < nHeap[nIndex])
  199.             smallest = nHeap[leftIdx];
  200.         if(nHeap[rightIdx] < nHeap[nIndex])
  201.             smallest = nHeap[leftIdx];
  202.        
  203.         // smallest <- either the index leftIdx, rightIdx, or nIndex whose
  204.         // corresponding heap node value is the smallest out of these three
  205.         // (however, ensure that leftIdx and rightIdx are actually children;
  206.         // use heapSize to determine this)
  207.        
  208.         if(smallest != nIndex)
  209.            
  210.         // if smallest != nIndex:
  211.         //    COMMENT: This means the node at nIndex has a child smaller than
  212.         //    itself at index smallest. This smallest child needs to come up
  213.         //    and replace the node at nIndex, and the node at nIndex needs to
  214.         //    come down to replace the smallest child. We then repeat the
  215.         //    process recursively at index smallest.
  216.  
  217.         //    swap node values at indexes smallest and nIndex
  218.             Heapify(smallest);
  219.     }
  220.  
  221.  
  222.     // The following methods, AddElement and its auxiliary method SiftUp, are
  223.     // not used with DoHeapSort.
  224.  
  225.     // DoHeapSort uses BuildHeap instead, which is a more efficient way (O(n))
  226.     // to build a heap starting from a list of numbers than AddElement. The way
  227.     // to build a heap using AddElement is to start with an empty heap and
  228.     // repeatedly add each element into the heap. This way is O(nlogn).
  229.     // However, AddElement is useful to add new elements into an existing heap
  230.     // once it has been built with BuildHeap.
  231.  
  232.     static void AddElement( int nNumber )
  233.     {
  234.         // Input: static fields nHeap, heapSize. nHeap must already be a valid
  235.         // min-heap.
  236.  
  237.         // Input: nNumber, a new node to add to the heap
  238.        
  239.         // Output: heap with nNumber added, heapSize increased by 1
  240.  
  241.         // Complexity: O(log(heapSize))
  242.         if(heapSize+1 > nHeap.length)
  243.         {
  244.               int[] doubleArray;
  245.               doubleArray = new int[2*(nHeap.length)];
  246.               for(int i=0; i<nHeap.length; i++)
  247.                   doubleArray[i]=nHeap[i];
  248.              
  249.  
  250.             heapSize++;
  251.             doubleArray[heapSize-1]=nNumber;
  252.             SiftUp(heapSize-1);
  253.            
  254.         }
  255.    
  256.         else {
  257.         heapSize++;
  258.         nHeap[heapSize-1]=nNumber;
  259.         SiftUp(heapSize-1);
  260.              }
  261.            
  262.         // Precondition: heapSize+1 <= nHeap.length
  263.         // If this is not the case, before running the algorithm, create a new
  264.         // array that is double the size of nHeap, copy the elements of nHeap
  265.         // into it, and assign nHeap to be the new larger array
  266.  
  267.         // Algorithm:
  268.  
  269.         // Increase heapSize by 1
  270.         // Copy nNumber to index heapSize-1 of the heap
  271.         // SiftUp(heapSize-1)
  272.     }
  273.    
  274.     static void SiftUp( int nNodeIndex )
  275.     {
  276.         // repeatedly sift up the element at nNodeIndex as long as its parent
  277.         // node is greater or the element is the root (this is similar to
  278.         // Heapify but it moves the element upwards instead of downwards)
  279.        
  280.         int index, temp;
  281.         if( nNodeIndex != 0 )
  282.         {
  283.             // Get the parent index so that we can
  284.             index = GetParentIndex( nNodeIndex );
  285.  
  286.             //compare parent with the number at the specified index
  287.             if( nHeap[index] > nHeap[nNodeIndex] )
  288.             {
  289.                 // Swap the parent and child.
  290.                 temp = nHeap[index];
  291.                 nHeap[index] = nHeap[index];
  292.                 nHeap[nNodeIndex] = temp;
  293.  
  294.                 // recursively call to sort
  295.                 SiftUp(index);
  296.             }
  297.         }
  298.        
  299.     }
  300.  
  301.     ///////////////////////////////////////////
  302.     //
  303.     // End of assignment code.
  304.     //
  305.     ///////////////////////////////////////////
  306.  
  307.     public static void setRandomArray(int n)
  308.     {
  309.         Random rnd = new Random();
  310.         nRandomNumbers = new int[n];
  311.         for( int i=0; i<nRandomNumbers.length; i++ )
  312.         {
  313.             nRandomNumbers[i] = rnd.nextInt( 500 );
  314.         }
  315.     }
  316.    
  317.     public static void main(String[] args)
  318.     {
  319.             System.out.println();
  320.         System.out.println();
  321.        
  322.         int[] array = {1,5,2,1,4,6};
  323.         DoBubbleSort(array);
  324.         System.out.println("BubbleSort:");
  325.         for(int y=0; y<array.length; y++)
  326.             System.out.printf("%d ",array[y]);
  327.        
  328.         System.out.println();
  329.         System.out.println();
  330.        
  331.         int[] array2 = {1,5,2,10,4,6,5,2,10,3,5,6};
  332.         DoInsertSort(array2);
  333.         System.out.println("InsertSort:");
  334.         for(int y=0; y<array2.length; y++)
  335.             System.out.printf("%d ",array2[y]);
  336.        
  337.         BuildHeap();
  338.     }
  339. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement