Sorting 2 dimensional arrays in Java - skipping the first index -
i have two-dimensional array in java looks this:
each element/job has a:
- job number in index[0];
- job arrival time in index[1]; and
- job burst time in index[2]
jobs[0][0] = 1 jobs[0][1] = 0 jobs[0][2] = 5 jobs[1][0] = 2 jobs[1][1] = 2 jobs[1][2] = 19 jobs[2][0] = 3 jobs[2][1] = 4 jobs[2][2] = 10 first, wanted sort them according arrival time according index[1] fortunately did using code:
arrays.sort(jobs, new comparator<int[]>(){ public int compare(int[] a, int[] b) { return a[1] - b[1]; } }); now, problem want sort according burst time according index[2]. here twist... how can able sort according burst time (index[2]) skipping first element? job[0] remain on top of array , sort remaining elements index[2] - burst time. this:
jobs[0][0] = 1 jobs[0][1] = 0 jobs[0][2] = 5 jobs[1][0] = 3 jobs[1][1] = 4 jobs[1][2] = 10 jobs[2][0] = 2 jobs[2][1] = 2 jobs[2][2] = 19 the jobs being sorted burst time job1 remaining on top. implementing code provided above better. thanks
a trivial way be:
int firstburst = jobs[0][2]; jobs[0][2] = integer.min_value; arrays.sort(jobs, new comparator<int[]>(){ public int compare(int[] a, int[] b) { // don't use subtraction, can lead underflows return a[2] < b[2] ? -1 : (a[2] == b[2] ? 0 : 1); } }); jobs[0][2] = firstburst; simply set burst of first item integer.min_value (the integer equivalent of minus infinity). way, guaranteed first item smallest, after sorting still first element. after sorting, reset burst of first item original value.
edit
by checking documentation verify arrays.sort stable, accidentally found simplest version solve problem: use
arrays.sort(t[] a, int fromindex, int toindex, comparator<? super t> c) then can directly:
arrays.sort(jobs, 1, jobs.length, new comparator<int[]>(){ public int compare(int[] a, int[] b) { // don't use subtraction, can lead underflows return a[2] < b[2] ? -1 : (a[2] == b[2] ? 0 : 1); } });
Comments
Post a Comment