Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: array 5*5

  1. #1
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    array 5*5

    I am new in c++. I want to write a program getting array 5*5 and then sort it horizontally.could you please help me? I do not know what should I do exactly!
    Thank you.

  • #2
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    Well, you probably know this:
    array[r][c]

    Correct?

    Well, suppose you were to sort the array row by row. I believe it would be correct to then say that the you can reduce each two dimensional array to a single one:
    row = array[r]
    sort(row);

    Now, we can't be so direct when it comes to columns. Well, I can propose two solutions:

    1. Create a new array "u" that can hold up to 5 elements. Store each element at each row that is at a specific column and sort that array. Then, restore it back into original array.
    2. Directly apply sort method to each column.

    I will be writing down the code for it because I feel like it will reduce confusion compared to if I explained it with pseudocode.

    For the first method, you would do something like:
    Code:
    for(int i = 0; i < 5; ++i) {
      int u[] = new int[5];
      for(int j = 0; j < 5; j++) {
        u[j] = array[j][i];
      }
      sort(u);
      for(int j = 0; j < 5; j++) {
        array[j][i] = u[j];
      }
    }
    For the second method, you would do something like:
    Code:
    for(int i = 0; i < 5; i++) {
      for(int j = 0; j < 4; j++) {
        int k = j + 1;
        for(int k = j+1; k > -1 && array[k][i] < array[j][i]; k--) {  // insertion sort
          swap(array[k][i], array[j][i]);
        }
      }
    }

  • Users who have thanked Apothem for this post:

    sabsa (12-16-2011)

  • #3
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts
    thank you so much for helping.I'll try that.


    what I'm writing is that attachment.
    the first one I'm writing in what you said.and the second one is what I'm write before.
    is this writing right?
    what should I do next?
    Attached Files Attached Files
    Last edited by sabsa; 12-16-2011 at 10:36 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •