Nxt3
Nxt3

Reputation: 2071

Sort 2x3 Matrix without using qsort

My teacher has assigned something I can't seem to figure out how to do without using qsort. We're given a 2x3 array, and he wants us to sort each row from min to max. I am not allowed to use qsort for the purposes of learning; in my opinion, this is difficult.

Here is what I have so far; currently, the program crashes. I assume this is because when it gets to the third column, there isn't anything in a fourth column [j+1], so it returns an error.

#include "stdafx.h"
#include <stdio.h>

int main() {

    int x[2][3] = { { 2, 3, -1 }, { 0, -3, 5 } }; //2x3 matrix; 2 rows, 3 columns
    void sortMinMax(int b[][3], int numRow, int numColumn); //function prototype

    sortMinMax(x, 2, 3);

    return 0;
}

void sortMinMax(int a[][3], int numRow, int numColumn) {

for (int i = 0; i < numRow; i++) {
    for (int j = 0; j < numColumn - 1; j++) {
        if (a[i][j + 1] < a[i][j]) { //swap values if the next number is less than the current number
            int temp = a[i][j];
            a[i][j] = a[i][j + 1];
            a[i][j + 1] = temp;
        }
        printf("%i\t", a[i][j]);
    }
    printf("\n");
}

return;
}

I appreciate any and all help!

Upvotes: 0

Views: 147

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

#include <stdio.h>

int main() {
    int x[2][3] = { { 2, 3, -1 }, { 0, -3, 5 } };
    void sortMinMax(int b[][3], int numRow, int numColumn);

    sortMinMax(x, 2, 3);
    for(int i = 0;i<2;++i){
        for(int j = 0;j<3;++j)
            printf("%i\t", x[i][j]);
        printf("\n");
    }
    return 0;
}

void swap(int *a, int *b){
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void sort3(int a[3]){
    if(a[0] > a[1])
        swap(&a[0], &a[1]);
    if(a[0] > a[2])
        swap(&a[0], &a[2]);
    if(a[1] > a[2])
        swap(&a[1], &a[2]);
}

void sortMinMax(int a[][3], int numRow, int numColumn) {
    for (int i = 0; i < numRow; i++) {
        sort3(a[i]);
    }
}

Upvotes: 0

Elalfer
Elalfer

Reputation: 5338

  1. I believe int i = 0; i <= numRow; i++ should be int i = 0; i < numRow; i++
  2. Why do you have if(i==0) & if(i==1) if you are doing the same stuff?
  3. It looks like you tried to implement bubble-sort-like algorithm, but you do only one pass over the data

Here is an example of bubble sort algorithm

for(int x=0; x<n; x++)
{
    for(int y=0; y<n-1; y++)
    {
        if(array[y]>array[y+1])
        {
            int temp = array[y+1];
            array[y+1] = array[y];
            array[y] = temp;
        }
    }
}

Slightly better alternative might be found @ http://www.sorting-algorithms.com/bubble-sort

for i = 1:n,
    swapped = false
    for j = n:i+1, 
        if a[j] < a[j-1], 
            swap a[j,j-1]
            swapped = true
    → invariant: a[1..i] in final position
    break if not swapped
end

Upvotes: 1

Related Questions