• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sortind2DArray  RSS feed

 
muscles wood
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Please have a look at the below code for sorting a 2D array nad correct me ,. I am not getting a correct output.

 
Liutauras Vilda
Sheriff
Posts: 4928
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems you used "Quote" tags instead of "Code". I corrected them for you.
 
Knute Snortum
Sheriff
Posts: 4288
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this output:

Original array{4, 2} {1, 7} {4, 5} {1, 2} {1, 1} {4, 1}

After sorting (1st dimension):{1, 7} {1, 2} {1, 1} {4, 2} {4, 5} {4, 1}

After sorting (second dimension):
{4, 2} {4, 5} {4, 1} {1, 7} {1, 2} {1, 1}

What were you expecting? Your second sort does not sort the second "dimension" (*) but the first in descending order.

* Java doesn't have 2d arrays, but arrays of arrays.
 
muscles wood
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is the expected output

{{1,1}, {1,2}, {1,7}, {4,1},{4,2},{4,5}}
 
muscles wood
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried but couldn't get the expected output
 
Knute Snortum
Sheriff
Posts: 4288
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This code is comparing and swapping arrays, but do you want to swap arrays, or elements? That is, are you swapping the first "dimension" or the second?
 
muscles wood
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thtas the question :

Write a method to sort a two-dimensional array using the following header:

public static void sort(int[][] m)
the method performs a primary sort on rows and a secondary sort on columns. For example, the following array

{{4,2}, {1,7}, {4,5},{1,2},{1,1},{4,1}}

Will be sorted to

{{1,1}, {1,2}, {1,7}, {4,1},{4,2},{4,5}}

Then write a tester program (named SortArray2.java) to test your method
 
Knute Snortum
Sheriff
Posts: 4288
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After sortArrayBubble you have the array correctly sorted in ascending order by the [row][0] element (the first "dimension). But sortArrayBubble1 just reverses that order, so it's not doing what you want.

Check that I'm correct in this.

Now write down what you have in the array after the first, correct sort: I'll start:

[0][0] = 1
[0][1] = 7
[1][0] = 1
[1][1] = 2
etc.

So what elements do you need to sort? What do they all have in common?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!