In: Computer Science
How is this method coded in Java?
int[] sortQuicksort(int[][] view)
sortQuicksort performs a quicksort sort on a view (a referential view of the master set of posts). sortQuicksort returns an array of profile information as detailed in the Data Structures section above. You may implement additional functions to support this sorting operation; however, take care that the profile information is accurately maintained and accounted for over any subsequent function calls.
/// Sorts (shallow) a set of references to posts in descending order
/// subject to the differential between ups and downs using a quicksort.
/// @param view A shallow copy of a set of posts
/// @return an array of profile information of 3 buckets with the
/// respective buckets containing a count of 0: allocations,
/// 1:comparisons, and 2: swaps
public static int[] sortQuicksort(int[][] view) {
// profile[0:allocs, 1:comparisons, 2:swaps]
int[] profile = new int[3];
// TODO : Implement Here
return profile;
}
Posts Data:
0001 505361 236677
0002 629710 727941
0003 414780 842861
0004 702957 401854
0005 862865 315572
0006 930013 609421
0007 326101 220500
0008 732457 404837
0009 878259 411163
0010 227645 638470
Answer:
public class BubbleSort {
public static void main(String[] args) {
int arr[][] = { { 11, 505361, 236677 }, { 2, 629710, 727941 }, { 3, 414780, 842861 }, { 4, 702957, 401854 },
{ 5, 862865, 315572 }, { 6, 930013, 609421 }, { 7, 326101, 220500 }, { 8, 732457, 404837 },
{ 9, 878259, 411163 }, { 10, 227645, 638470 } };
int[] profile=sortBubble(arr);
System.out.println(profile[0]+":allocations");
System.out.println(profile[1]+":comparisons");
System.out.println(profile[2]+":swaps");
for (int[] is : arr) {
for (int i : is) {
System.out.print(i+" ");
}
System.out.println();
}
}
public static int[] sortBubble(int[][] view) {
int profile[] = new int[3];
int n = view.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (view[j - 1][0] > view[j][0] || (view[j - 1][0] == view[j][0] && view[j - 1][1] > view[j][1]) || (view[j - 1][0] == view[j][0] && view[j - 1][1] == view[j][1] && view[j - 1][2] > view[j][2]) ) {
// swap elements
temp = view[j - 1][0];
view[j - 1][0] = view[j][0];
view[j][0] = temp;
temp = view[j - 1][1];
view[j - 1][1] = view[j][1];
view[j][1] = temp;
temp = view[j - 1][2];
view[j - 1][2] = view[j][2];
view[j][2] = temp;
profile[2]+=3;
if(view[j - 1][0] == view[j][0]){
profile[1]+=3;
}else if(view[j - 1][0] == view[j][0] && view[j - 1][1] == view[j][1]){
profile[1]+=6;
}else{
profile[1]+=1;
}
profile[0]+=9;
}
}
}
return profile;
}
}