Search code examples
c++algorithmnested-loopsbubble-sort

1D Array, how to make rows and Columns C++


I was wondering how I would write a one dimensional array with 10 elements into 2 rows and 5 columns? I am doing this to try to organize my bubbleSort method.

#include <iostream>
#include <string>
using namespace std;

const int NUM_ELEMENTS = 10;
void bubbleSort(int data[]){
    srand(time(0));
 int temp = 0;
 for(int i = 0; i<NUM_ELEMENTS;i++){
     data[i] = rand()%10;
     }
 for(int b = 0; b<NUM_ELEMENTS-1; b++){

    for(int x= 0; x<NUM_ELEMENTS-1;x++)
    {

     if(data[x]>data[x+1]){
      temp = data[x];
      data[x] = data[x+1];
      data[x+1] = temp;

     }

    }
 }
for(int i = 0; i<NUM_ELEMENTS; i++)    
printf("%4d",data[i]);   
}
int main()
{
int data[NUM_ELEMENTS];
bubbleSort(data); 
}

Solution

  • I think this is what your trying to do. Printing a one-dim array into a two-dim array.

    int [] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int rows = 2;
        int columns = 5;
        for (int row = 0; row < rows; row++) {
            for (int column = 0; column < columns; column++) {
                System.out.printf("%d "+data[row * columns + column]);
            }
            System.out.println();
        }
    

    output:

    1 2 3 4 5 
    6 7 8 9 10