Advertisement
Guest User

Untitled

a guest
May 26th, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.37 KB | None | 0 0
  1.  
  2. import java.util.*;
  3. import java.math.BigDecimal;
  4.  
  5.  
  6.  
  7.  
  8. public class SortDemo3
  9. {
  10.     public static final int NO_OF_RECORDS = 10;
  11.     public static final int STRING_LENGTH = 4;
  12.    
  13.     private static void printRecords(Data records) {
  14.         for(int index = 0; index < records.size(); index++) {
  15.             print(records.recordAt(index).getId() + "\t" +
  16.                     records.recordAt(index).getVitality() + "\t" + records.recordAt(index).getTreatment());
  17.         }
  18.     }
  19.     public static void print(String s) {
  20.         System.out.println(s);
  21.     }
  22.     public static byte[] random(int len) {
  23.         byte buffer[] = new byte[len];
  24.        
  25.         for(int i = 0; i < len; i++) {
  26.             buffer[i] = (byte)(Math.random() * 26 + 97);
  27.         }      
  28.         return buffer;     
  29.     }  
  30.     public static void main(String[] args)
  31.     {
  32.         SortObj soBubbleSort = new SortObj("Bubble Sort");
  33.         SortObj soInsertionSort = new SortObj("Insertion Sort");
  34.         SortObj soSelectionSort = new SortObj("Selection Sort");
  35.         SortObj soQuickSort = new SortObj("Quick Sort");
  36.         int noOfRecords = NO_OF_RECORDS;
  37.         Record[] rec = new Record[NO_OF_RECORDS];
  38.         String name;
  39.                
  40.         int iTotal = 0;
  41.        
  42.         Random generator = new Random();
  43.         Scanner in = new Scanner(System.in);
  44.         int iOption = 1000;
  45.        
  46.         for(int j = 0; j < noOfRecords; j++)
  47.         {
  48.             name = new String(random(STRING_LENGTH));
  49.             rec[j] = new Record();
  50.             rec[j].setTreatment(name);
  51.             rec[j].setId(new String(random(6)));
  52.             int iVitality = generator.nextInt(6);iTotal = (iVitality == 0) ? ++iTotal:iTotal;          
  53.             rec[j].setVitality(Integer.toString(iVitality));
  54.             soBubbleSort.getData().addRecord(rec[j]);
  55.             soInsertionSort.getData().addRecord(rec[j]);
  56.             soSelectionSort.getData().addRecord(rec[j]);
  57.             soQuickSort.getData().addRecord(rec[j]);
  58.         }
  59.         print("\t------INITIAL DATA STATISTICS------");
  60.         print(noOfRecords+" records generated successfully.");
  61.         BigDecimal bdResult = new BigDecimal((((double)iTotal/noOfRecords)*100)).setScale(1,BigDecimal.ROUND_HALF_UP);
  62.         print(bdResult+ "% ("+iTotal+") of our indexed plants are dead (vitality 0)");
  63.         print("meaning that " +(new BigDecimal((((double)(noOfRecords-iTotal)/noOfRecords)*100)).setScale(1,BigDecimal.ROUND_HALF_UP)) +
  64.               "% (" +(noOfRecords-iTotal)+ ") of our specimens are alive.");
  65.         print("\t------INITIAL DATA STATISTICS------");
  66.        
  67.         while(iOption != 0) {
  68.             print("Menu");
  69.             print("1.   BubbleSort record archive");
  70.             print("2.   InsertionSort record archive");
  71.             print("3.   SelectionSort record archive");
  72.             print("4.   QuickSort record archive");
  73.             print("5.   All of them!");
  74.             print("0.   Quit");
  75.             iOption = in.nextInt();
  76.            
  77.             if(iOption != 0) {
  78.                 print("\nThe sorting of the strings is about to start.");
  79.             }
  80.             switch(iOption) {
  81.                 case 1: case 5:
  82.                     print("\nThe Bubble Sort");
  83.                    
  84.                     print("\n\nThe unsorted data is:\n");
  85.                     printRecords(soBubbleSort.getData());
  86.                     soBubbleSort.startTimer();
  87.                     SortBy.bubble1f(soBubbleSort.getData());
  88.                     print("\n\nThe sorted data is (1 field):\n");
  89.                     printRecords(soBubbleSort.getData());
  90.                     SortBy.bubble2f(soBubbleSort.getData());
  91.                     soBubbleSort.stopTimer();
  92.                     print("\n\nThe sorted data is (2 fields):\n");
  93.                     printRecords(soBubbleSort.getData());
  94.                     print("---------------\n");
  95.                     if(iOption != 5) {
  96.                         print("Sorting stats:");
  97.                         soBubbleSort.statistics();
  98.                         print("\n\n");
  99.                         break;
  100.                     }
  101.                 case 2:
  102.                     print("\nThe Insertion Sort");
  103.                    
  104.                     print("\n\nThe unsorted data is:\n");
  105.                     printRecords(soInsertionSort.getData());
  106.                     soInsertionSort.startTimer();
  107.                     SortBy.insertion1f(soInsertionSort.getData());
  108.                     print("\n\nThe sorted data is (1 field):\n");
  109.                     printRecords(soInsertionSort.getData());
  110.                     SortBy.insertion2f(soInsertionSort.getData());
  111.                     soInsertionSort.stopTimer();
  112.                     print("\n\nThe sorted data is (2 fields):\n");
  113.                     printRecords(soInsertionSort.getData());
  114.                     print("---------------\n");
  115.                     if(iOption != 5) {
  116.                         print("Sorting stats:");
  117.                         soInsertionSort.statistics();
  118.                         print("\n\n");
  119.                         break;
  120.                     }
  121.                 case 3:
  122.                     print("\nThe Selection Sort");
  123.                    
  124.                     print("\n\nThe unsorted data is:\n");
  125.                     printRecords(soSelectionSort.getData());
  126.                     soSelectionSort.startTimer();
  127.                     SortBy.selection1f(soSelectionSort.getData());
  128.                     print("\n\nThe sorted data is (1 field):\n");
  129.                     printRecords(soSelectionSort.getData());
  130.                     SortBy.selection2f(soSelectionSort.getData());
  131.                     soSelectionSort.stopTimer();
  132.                     print("\n\nThe sorted data is (2 fields):\n");
  133.                     printRecords(soSelectionSort.getData());
  134.                     print("---------------\n");
  135.                     if(iOption != 5) {
  136.                         print("Sorting stats:");
  137.                         soSelectionSort.statistics();
  138.                         print("\n\n");
  139.                         break;
  140.                     }
  141.                 case 4: // doesnt work
  142.                     print("\nThe Quick Sort");
  143.                    
  144.                     print("\n\nThe unsorted data is:\n");
  145.                     printRecords(soQuickSort.getData());
  146.                     soQuickSort.startTimer();
  147.                     soQuickSort.setData(SortBy.quickSort(soQuickSort.getData(),1));
  148.                     print("\n\nThe sorted data is (1 field):\n");
  149.                     printRecords(soQuickSort.getData());
  150.                     soQuickSort.setData(SortBy.quickSort(soQuickSort.getData(),2));
  151.                     soQuickSort.stopTimer();
  152.                     print("\n\nThe sorted data is (2 fields):\n");
  153.                     printRecords(soQuickSort.getData());
  154.                     print("---------------\n");
  155.                     if(iOption != 5) {
  156.                         print("Sorting stats:");
  157.                         soQuickSort.statistics();
  158.                         break;
  159.                     } else {
  160.                         print("Overall stats:");
  161.                         soBubbleSort.statistics();
  162.                         soInsertionSort.statistics();
  163.                         soSelectionSort.statistics();
  164.                         soQuickSort.statistics();
  165.                        
  166.                     }
  167.                 case 0:
  168.                     print("Quitting...");
  169.                     iOption = 0;
  170.                     break;
  171.                 default:
  172.                     print("Not a valid option");           
  173.             }          
  174.         }      
  175.     }
  176. }
  177.  
  178. class Tools extends Display {
  179.     private static final Runtime s_runtime = Runtime.getRuntime();
  180.    
  181.     public static int toInt(String n) {
  182.         return Integer.parseInt(n);
  183.     }
  184.     public static int toInt(long l) {
  185.         return (int)l;
  186.     }
  187.     public static long getTime() {
  188.         return new Date().getTime();
  189.     }
  190.     protected static long getMemoryStatus()
  191.     {
  192.         long mem;
  193.  
  194.         runGC();
  195.         mem = usedMemory();
  196.         return mem;
  197.     }
  198.  
  199.     private static void runGC()
  200.     {
  201.         for(int count = 0; count < 10; ++count)
  202.         {
  203.             _runGC();
  204.         }
  205.     }
  206.  
  207.     private static void _runGC()
  208.     {
  209.         long usedMem1 = usedMemory();
  210.         long usedMem2 = Long.MAX_VALUE;
  211.  
  212.         for(int i = 0; usedMem1 < usedMem2 && i < 5000; ++i)
  213.         {
  214.             s_runtime.runFinalization();
  215.             s_runtime.gc();
  216.             Thread.currentThread();
  217.             Thread.yield();
  218.             usedMem2 = usedMem1;
  219.             usedMem1 = usedMemory();
  220.         }
  221.     }
  222.  
  223.     private static long usedMemory()
  224.     {
  225.         return s_runtime.totalMemory() - s_runtime.freeMemory();
  226.     }
  227.  
  228. }
  229.  
  230. class SortObj extends Tools {
  231.     private String sName;
  232.     private long lProcessStart;
  233.     private long lProcessEnd;
  234.     private long lSortDuration = 0;
  235.     private long lInitialMem;
  236.     private long lEndMem;
  237.     private long lMemUse = 0;
  238.     private Data sortData = new Data();
  239.  
  240.     public SortObj(String s) {
  241.         this.sName = s;
  242.     }
  243.    
  244.     public Data getData() {
  245.         return this.sortData;
  246.     }
  247.     public void setData(Data d) {
  248.         this.sortData = d;
  249.     }
  250.     public void startTimer() {
  251.         this.setStartTime(getTime());
  252.         this.setInitialMem(getMemoryStatus());
  253.     }
  254.     public void stopTimer() {
  255.         this.setEndTime(getTime());
  256.         this.setEndMem(getMemoryStatus());
  257.        
  258.         if(this.getStartTime() > 0) this.setSortDuration(this.getEndTime()-this.getStartTime());
  259.     }
  260.     private void setStartTime(long lProcessStart) {
  261.         this.lProcessStart = lProcessStart;
  262.     }
  263.     private long getStartTime() {
  264.         return lProcessStart;
  265.     }
  266.     private void setEndTime(long lProcessEnd) {
  267.         this.lProcessEnd = lProcessEnd;
  268.     }
  269.     private long getEndTime() {
  270.         return lProcessEnd;
  271.     }
  272.     public void setSortDuration(long lSortDuration) {
  273.         this.lSortDuration = lSortDuration;
  274.     }
  275.     public long getSortDuration() {
  276.         return lSortDuration;
  277.     }
  278.     private void setInitialMem(long lInitialMem) {
  279.         this.lInitialMem = lInitialMem;
  280.     }
  281.     private long getInitialMem() {
  282.         return lInitialMem;
  283.     }
  284.     private void setEndMem(long lEndMem) {
  285.         this.lEndMem = lEndMem;
  286.        
  287.         if(!Integer.toString(toInt(this.getInitialMem())).equals(null)) this.setMemUsage(this.getEndMem()-this.getInitialMem());
  288.     }
  289.     private long getEndMem() {
  290.         return lEndMem;
  291.     }
  292.     private void setMemUsage(long lMemUse) {
  293.         this.lMemUse = lMemUse;
  294.     }
  295.     public long getMemUsage() {
  296.         return Math.abs(lMemUse);
  297.     }
  298.     public void setName(String sName) {
  299.         this.sName = sName;
  300.     }
  301.     public String getName() {
  302.         return sName;
  303.     }
  304.     public void statistics() {
  305.         showStatistics(this.getName(), this.getSortDuration(), this.getMemUsage());
  306.     }
  307. }
  308.  
  309. class SortBy extends Tools {
  310.     public static void bubble1f(Data elements) {
  311.         int n = elements.size();
  312.         boolean swapMade = true;
  313.         Record temp;
  314.         int passNo = 0;
  315.  
  316.         while(swapMade) {
  317.             passNo++;
  318.             swapMade = false;
  319.             for(int i = 0; i < n - passNo; i++) {
  320.                 if (elements.recordAt(i).getTreatment().compareTo(elements.recordAt(i+1).getTreatment()) > 0) {
  321.                     temp = elements.recordAt(i + 1);
  322.                     elements.removeRecordAt(i + 1);
  323.                     elements.addRecord(i, temp);
  324.                     swapMade = true;
  325.                 }                  
  326.             }
  327.         }      
  328.     }
  329.     public static void bubble2f(Data elements) {
  330.         int n = elements.size();
  331.         boolean swapMade = true;
  332.         Record temp;
  333.         int passNo = 0;
  334.  
  335.         while(swapMade) {
  336.             passNo++;
  337.             swapMade = false;
  338.             for(int i = 0; i < n - passNo; i++) {
  339.                 if (elements.recordAt(i).getVitality().compareTo(elements.recordAt(i + 1).getVitality()) > 0) {
  340.                     //next if is important to make sure we sort by 2 fields PROPERLY.
  341.                     if(toInt(elements.recordAt(i).getVitality()) >= toInt(elements.recordAt(i+1).getVitality())) {
  342.                         temp = elements.recordAt(i + 1);
  343.                         elements.removeRecordAt(i + 1);
  344.                         elements.addRecord(i + 1, elements.recordAt(i));
  345.                         elements.removeRecordAt(i);
  346.                         elements.addRecord(i, temp);
  347.                         swapMade = true;
  348.                     }                  
  349.                 }              
  350.             }          
  351.         }
  352.     }
  353.     public static Data InsertionSort(Data rawdata){
  354.         // Insertion Sort Method
  355.         // Starts at the beginning of the list, compares the next object to the previous objects and shifts down until in the correct position
  356.        
  357.         for (int i=1;i<rawdata.size();i++){
  358.                 // Start at the second element of the list and compare each preceding element
  359.                
  360.                 int cur = i;
  361.                 Record held = (Record) rawdata.remove(cur); // Hold the element in limbo
  362.                
  363.                 while (cur > 0 && toInt(held.getVitality()) < toInt(((Record) rawdata.elementAt(cur-1)).getVitality())) {
  364.                         // Compare the held item to the previous item. If it is smaller or not at the beining of the list then continue looping
  365.                         cur--;
  366.                 }
  367.                
  368.                 //once the right position is found, take the held element and insert it into that position and continue to the next object
  369.                 rawdata.insertElementAt(held, cur);
  370.         }
  371.         return rawdata;
  372.     }
  373.     public static void insertion1f(Data elements) {
  374.         int n = elements.size();
  375.  
  376.         for (int i = n - 1; i > 0; i--) {
  377.             Record current = elements.recordAt(i-1);
  378.             int j = i - 1;
  379.             for (; j < n - 1 && current.getTreatment().compareTo(elements.recordAt(j+1).getTreatment()) > 0; j++) {
  380.                 elements.setElementAt(elements.recordAt(j+1), j);              
  381.             }
  382.             elements.setElementAt(current, j);     
  383.         }
  384.     }
  385.     public static void insertion2f(Data elements) {
  386.         int n = elements.size();
  387.  
  388.         for (int i = n - 1; i > 0; i--) {
  389.             Record current = elements.recordAt(i-1);
  390.             int j = i - 1;
  391.             for (; j < n - 1 && current.getVitality().compareTo(elements.recordAt(j+1).getVitality()) > 0; j++) {
  392.                 try {
  393.                     if(toInt(elements.recordAt(i).getVitality()) >= toInt(elements.recordAt(i+1).getVitality())) {
  394.                         elements.setElementAt(elements.recordAt(j+1), j);      
  395.                     }
  396.                 } catch(Exception e) {}                
  397.             }
  398.             elements.setElementAt(current, j);     
  399.         }
  400.     }
  401.     public static void selection1f(Data elements) {
  402.         int n = elements.size();
  403.         for (int i = 0; i < n - 1; i++) {
  404.             Record current = elements.recordAt(i);
  405.             int k = i;
  406.             for (int j = i + 1; j <= n - 1; j++) {
  407.                 if (current.getTreatment().compareTo(elements.recordAt(j).getTreatment()) > 0) {
  408.                     k = j;
  409.                     current = elements.recordAt(k);
  410.                 }
  411.             }
  412.             if (k != i) {
  413.                 elements.removeRecordAt(k);
  414.                 elements.addRecord(i, current);
  415.             }
  416.         }
  417.     }
  418.     public static void selection2f(Data elements) {
  419.         int n = elements.size();
  420.         for (int i = 0; i < n - 1; i++) {
  421.             Record current = elements.recordAt(i);
  422.             int k = i;
  423.             for (int j = i + 1; j <= n - 1; j++) {
  424.                 if (current.getVitality().compareTo(elements.recordAt(j).getVitality()) > 0) {
  425.                     if(toInt(elements.recordAt(i).getVitality()) >= toInt(elements.recordAt(i+1).getVitality())) {
  426.                         k = j;
  427.                         current = elements.recordAt(k);
  428.                     }                  
  429.                 }
  430.             }
  431.             if (k != i) {
  432.                 elements.removeRecordAt(k);
  433.                 elements.addRecord(i, current);
  434.             }
  435.         }
  436.     }
  437.     private static void quickSortMain(Data rawdata, int low, int high) {
  438.        
  439.         int left = low;        
  440.         int right = high;      
  441.         Record pivot = (Record) rawdata.elementAt((left+right)/2);
  442.  
  443.         do {
  444.                 while (toInt(((Record) rawdata.elementAt(left)).getVitality()) < toInt(pivot.getVitality())) left++;          
  445.                 while (toInt(((Record) rawdata.elementAt(right)).getVitality()) > toInt(pivot.getVitality())) right--;          
  446.  
  447.                 if (left <= right) {
  448.                         Collections.swap(rawdata, left, right);
  449.                         left++;
  450.                         right--;
  451.                 }
  452.  
  453.         }while(left <= right);
  454.  
  455.         if (low < right) quickSortMain(rawdata, low, right);    
  456.         if (left < high) quickSortMain(rawdata, left, high);    
  457.  
  458.     }
  459.  
  460.     private static void quickSortSub(Data rawdata, int low, int high){
  461.        
  462.         int left = low;        
  463.         int right = high;      
  464.         Record pivot = (Record) rawdata.elementAt((left+right)/2);
  465.  
  466.         do {
  467.                 while (((Record) rawdata.elementAt(left)).getTreatment().compareTo(pivot.getTreatment()) < 0) left++;
  468.                 while (((Record) rawdata.elementAt(right)).getTreatment().compareTo(pivot.getTreatment()) > 0) right--;    
  469.  
  470.                 if (left <= right) {
  471.                         Collections.swap(rawdata, left, right);
  472.                         left++;
  473.                         right--;
  474.                 }
  475.         }while(left <= right);
  476.  
  477.         if (low < right) quickSortSub(rawdata, low, right);    
  478.         if (left < high) quickSortSub(rawdata, left, high);    
  479.     }
  480.     public static Data quickSort(Data rawdata, int fields) {
  481.        
  482.         quickSortMain(rawdata, 0, rawdata.size()-1);  
  483.  
  484.         int lbound[] = new int[6];
  485.         int ubound[] = new int[6];
  486.         int index = 0;          
  487.         for (int i=0;i<6;i++){
  488.             if (toInt(((Record) rawdata.elementAt(index)).getVitality()) != i) {
  489.                 continue;
  490.             }else{
  491.                 lbound[i] = index;
  492.             }
  493.             while(toInt(((Record) rawdata.elementAt(index)).getVitality()) == i && index<rawdata.size()-1) index++;
  494.             ubound[i] = (index == rawdata.size()-1) ? index : index-1;         
  495.         }
  496.  
  497.         if(fields == 2) {
  498.             for (int i=0;i<6;i++) quickSortSub(rawdata, lbound[i], ubound[i]);
  499.         }    
  500.         return rawdata;
  501.     }
  502. }
  503.  
  504. class Record
  505. {
  506.     private String id;
  507.     private String vitality;
  508.     private String treatment;
  509.  
  510.    
  511.     public void setTreatment(String name) {
  512.         this.treatment = name;
  513.     }  
  514.     public void setVitality(String vitality) {
  515.         this.vitality = vitality;
  516.     }
  517.     public void setId(String id) {
  518.         this.id = id;
  519.     }
  520.  
  521.     public String getId() {
  522.         return id;
  523.     }
  524.     public String getTreatment() {
  525.         return treatment;
  526.     }
  527.     public String getVitality() {
  528.         return vitality;
  529.     }
  530. }
  531.  
  532. class Data extends Vector<Object>
  533. {
  534.     /**
  535.      *
  536.      */
  537.     private static final long serialVersionUID = -5786785034903546138L;
  538.  
  539.  
  540.     public Record recordAt(int index)
  541.     {
  542.         return (Record) elementAt(index);
  543.     }
  544.    
  545.     public void addRecord(Record record)
  546.     {
  547.         addElement(record);
  548.     }
  549.    
  550.     public void addRecord(int position, Record record)
  551.     {
  552.         add(position, record);
  553.     }
  554.    
  555.     public void removeRecordAt(int position)
  556.     {
  557.         removeElementAt(position);
  558.     }
  559. }
  560.  
  561. class Display
  562. {
  563.     public static void showStatistics(String operation, long millis, long space)
  564.     {
  565.         showTime(operation, millis);
  566.         showMemory(operation, space);  
  567.     }
  568.  
  569.     private static void showTime(String operation, long millis)
  570.     {
  571.         long millisecs = millis % 1000;
  572.         long secsTemp = (millis - millisecs) / 1000;
  573.         long secs = secsTemp % 60;
  574.         long mins = (secsTemp - secs) / 60;
  575.         String padding1;
  576.         String padding2;
  577.         String padding3;
  578.         int padLength;
  579.  
  580.         padLength = 20 - operation.length();
  581.         padding1 = new String();
  582.         for(int index = 0; index < padLength; index++)
  583.         {
  584.             padding1 = padding1.concat(" ");
  585.         }
  586.         if(secs < 10)
  587.         {
  588.             padding2 = new String("0");
  589.         }
  590.         else
  591.         {
  592.             padding2 = new String("");
  593.         }
  594.         if(millisecs < 10)
  595.         {
  596.             padding3 = new String("00");
  597.         }
  598.         else if(millisecs < 100)
  599.         {
  600.             padding3 = new String("0");
  601.         }
  602.         else
  603.         {
  604.             padding3 = new String("");
  605.         }
  606.         System.out.print(operation + padding1 + " time: " + mins + ":" + padding2 + secs + ":");
  607.         System.out.print(padding3 + millisecs);
  608.     }
  609.  
  610.     private static void showMemory(String operation, long space)
  611.     {
  612.         if(!operation.equals("Saving to disk"))
  613.         {
  614.             System.out.println("\tSpace used: " + space + " bytes");
  615.         }
  616.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement