Sort 2x3 Matrix without using qsort - c

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!

I believe int i = 0; i <= numRow; i++ should be int i = 0; i <
numRow; i++
Why do you have if(i==0) & if(i==1) if you are doing the same stuff?
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

#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]);
}
}

Related

Unable to find the optimal cost of pairing elements of two sets

Given two sets of natural number A and B of size n such that each member of A has to be paired to at at most one member of B. There is also cost associated with each pairing i.e if the absolute difference b\l sum of all n-length possible pair permutations of elements of A with B.
The following (crude and far from being optimized and safe -- I used a global variable: horror!) code does the job:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)
int factorial(int N) {
int product = 1;
for (int j = 1; j <= N; j++)
product *= j;
return product;
}
// Prints the array
void printArr(int a[], int n)
{
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
// Stores the array
void storeArr(int a[], int n, int counter, int** out)
{
for (int i = 0; i < n; i++) {
out[counter][i] = a[i];
}
}
int get_cost(int a, int b) {
int diff = abs(a - b);
if (diff >= 5 && diff < 10) {
return 0;
}
else if (diff < 5) {
return 1;
}
else {
return 2;
}
}
int cost_perm(int* a, int* b, int n) {
int cost = 0;
for (int i = 0; i < n; ++i) {
cost += get_cost( a[i], b[i] );
}
return cost;
}
// Globals are bad but...
int counter;
// Generating permutation using Heap Algorithm
void heapPermutation(int a[], int size, int n, int** out)
{
// if size becomes 1 then stores the obtained
// permutation
if (size == 1) {
storeArr(a, n, counter++, out);
return;
}
for (int i = 0; i < size; i++) {
heapPermutation(a, size - 1, n, out);
// if size is odd, swap 0th i.e (first) and
// (size-1)th i.e (last) element
if (size % 2 == 1)
SWAP(a[0], a[size - 1], int);
// If size is even, swap ith and
// (size-1)th i.e (last) element
else
SWAP(a[i], a[size - 1], int);
}
}
// Driver code
int main()
{
int a[] = { 169, 165, 161, 131, 145 };
int b[] = { 214, 174, 218, 188, 168 };
int n = sizeof a / sizeof a[0];
int numperm = factorial(n);
int** perm_of_a = calloc(numperm, sizeof(int*));
int** perm_of_b = calloc(numperm, sizeof(int*));
for (int i = 0; i < numperm; ++i) {
perm_of_a[i] = calloc(n, sizeof(int));
perm_of_b[i] = calloc(n, sizeof(int));
}
counter = 0;
heapPermutation(a, n, n, perm_of_a);
counter = 0;
heapPermutation(b, n, n, perm_of_b);
int min_cost = 1000;
int cost;
int mina = 0;
int minb = 0;
for (int i = 0; i < numperm; ++i) {
for (int j = 0; j < numperm; ++j) {
cost = cost_perm(perm_of_a[i], perm_of_b[j], n);
if (cost < min_cost) {
min_cost = cost;
mina = i;
minb = j;
}
}
}
printArr( perm_of_a[mina], n );
printArr( perm_of_b[minb], n );
printf( "%d\n", min_cost );
return 0;
}
You are trying to find one individual pair at each iteration, but you want to minimize the cost over all permutations.
You need to figure out how to generate all permutations of a vector and use code like this:
for permuted_A in all_permutations_of_A
for permuted_B in all_permutations_of_B
cost = cost(permuted_A, permuted_B)
if cost < min_cost
min_cost = cost
min_permuted_A = permuted_A
min_permuted_B = permuted_B
Once you figure out how to enumerate the permutations, the rest will be trivial.

iterative permute function in C

I'm trying to write an iterative function that computes all the permutations of an array of numbers given in input.
Here is the code I've written so far.
void permute(int *a, int size){
int j=0, i, h=0, m;
bool flag=true;
int f = factorial(size);
int *arr, *res;
int counter=0;
arr = malloc(f*sizeof(int));
for(i=0; i<f; i++)
arr[i] = 0;
while (j < f) {
if(arr[j]<j)
{
if(j%2 == 0)
{
swap(a[0],a[j]);
} else {
swap(a[arr[j]], a[j]);
}
arr[j]++;
j=0;
} else{
arr[j] = 0;
j++;
}
printf("%d\n",a[j] );
}
}
The code doesn't compute well all the permutations and goes into a long loop. Can someone help me, please? Thanks to everyone.
Your code is close but includes some problems. For instance, the while loop
while (j < f) will assign j to a value out of bound of the array a.
Instead would you please try:
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i;
int y = 1;
for (i = 1; i <= x; i++) {
y *= i;
}
return y;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(int *a, int size)
{
int i, j = 0;
int f = factorial(size);
int *arr;
arr = calloc(f, sizeof(int)); // the members are initialized to 0
// print the original array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
while (j < size) {
if (arr[j] < j) {
if (j % 2 == 0) {
swap(a + 0, a + j);
} else {
swap(a + arr[j], a + j);
}
// print the rearranged array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
arr[j]++;
j = 0;
} else {
arr[j] = 0;
j++;
}
}
free(arr);
}
int main()
{
int a[] = {1, 2, 3}; // example
permute(a, sizeof a / sizeof a[0]); // the 2nd argument is the array length
return 0;
}
Output of the example:
1 2 3
2 1 3
3 1 2
1 3 2
2 3 1
3 2 1

A program sort array by remainder 3

I was requested to write an effecient function with running time n which sort array by the remainder of 3 the program puts the elements which the remainder from dividing in 3 is 0 afterwards the elements that the remainder is 1 and afterwards 2
for example the array {7, 16, 3, 28, 12, 31, 14, 12}
will be sortes that way {12, 3, 12, 28, 16, 31, 7, 14}
so I tries to write an efficient function but it have not cover all cases and does not works for all arrays
int arr[] = { 7,16,3,28,12,31,14,12 };
int rem0 = 0, rem1 = 1, rem2 = 2;
for (int i = 0; i < 8; i++) {
if (arr[i] % 3 == 0)
rem0++;
if (arr[i] % 3 == 1)
rem1++;
if (arr[i] % 3 == 2)
rem2++;
}
int k = rem0, p = 0, m = 0 = 0;
for (int i = 0; i < 8; i++) {
while (rem0-k){
swap(&arr[i], &arr[rem0 - k]);
k--;
}
if (arr[i] % 3 == 1 && rem0+m<7) {
swap(&arr[i], &arr[rem0 + m]);
m++;
}
if (arr[i] % 3 == 1 && rem0 + rem1 + p<7) {
swap(&arr[i], &arr[rem0+rem1 + p]);
p++;
}
}
for (int l = 0;l <8;l++) {
printf("%d\n", arr[l]);
}
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
swap switch elements,
Can anyone tells me how can I fix that?
thanks:)
Since you want your function to run in O(n) time, you cannot sort the array completely. All you need to do is put all the elements in 3 buckets.
The following algorithm runs in 2 phases.
//First we count the number of elements in each bucket
int count[3] ={0, 0, 0};
for (int i = 0; i < NUM_ELEMENTS; i++) {
count[arr[i]%3]++;
}
Now that we have the number of elements, we can calculate the offsets of each bucket and create and output array
int output[NUM_ELEMENTS]; // In place bucketing can also be done using swaps
count[2] = count[0] + count[1];
count[1] = count[0];
count[0] = 0;
for (int i = 0; i < NUM_ELEMENTS; i++) {
output[count[arr[i]%3]] = arr[i];
count[arr[i]%3]++;
}
// Finally print the array
for (int i = 0; i < NUM_ELEMENTS; i++) {
printf("%d", output[i]);
}
Demo on Ideone
Here is the solution which you are looking for which uses the same array:
#include <stdio.h>
#define REMINDER 3
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,0};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int idx=0;
for (int r=0; r<REMINDER; r++) {
for (int i=0; i<arr_size; i++) {
if (arr[i]%REMINDER==r) {
swap(&arr[idx++], &arr[i]);
}
}
}
for (int i=0; i<arr_size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Here is a another solution which is just simpler by using other place to store the result:
#include <stdio.h>
#define REMINDER 3
#define ARR_SIZE 10
int main()
{
int arr[ARR_SIZE] = {1,2,3,4,5,6,7,8,9,0};
int arr_sorted[ARR_SIZE];
int idx=0;
for (int r=0; r<REMINDER; r++) {
for (int i=0; i<ARR_SIZE; i++) {
if (arr[i]%REMINDER==r) {
arr_sorted[idx++]=arr[i];
}
}
}
for (int i=0; i<ARR_SIZE; i++) {
printf("%d ", arr_sorted[i]);
}
return 0;
}
Here's a 1-pass in-place Dutch national flag algorithm implementation (thanks to #Virgile who pointed out the algorithm)
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
// Dutch National Flag (see xlinux.nist.gov/dads/HTML/DutchNationalFlag.html)
void sort3dnf(int *a, size_t n) {
int *bot = a;
int *mid = a;
int *top = a + n - 1;
while (mid <= top) {
switch (*mid % 3) {
default: swap(bot++, mid++); break;
case 1: mid++; break;
case 2: swap(mid, top--); break;
}
}
}
See ideone.com/6QXXCN
hey thanks for the advice
sadly we had requested to write the code
without any added array
I will be very glad if you could help me to
solve the issue
thanks :)
hey thanks for the advice sadly we had requested to write the code without any added array I will be very glad if you could help me to solve the issue thanks :)
Here is the answer without adding any extra array:
#include <stdio.h>
#define REMINDER 3
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,0};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int idx=0;
for (int r=0; r<REMINDER; r++) {
for (int i=0; i<arr_size; i++) {
if (arr[i]%REMINDER==r) {
swap(&arr[idx++], &arr[i]);
}
}
}
for (int i=0; i<arr_size; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Understanding Heaps

Every reference I look at to learn about heaps says that the sift_down approach to building heaps is the ideal way, but does this mean that it is still possible to build a heap using sift_up? If so, why is sift_down preferred? I'm trying to get a better understanding of these types of things for an algorithms course I am taking. I'd like to try to implement a build_heap function that uses sift_up, but so far I haven't had any luck, though I have managed to get it to work using sift_down.
Any ideas, suggestions, or references that anyone could share? Here's a few functions I'm struggling with at the moment:
#include <stdio.h>
void bottom_up_heapsort(int*, int);
void heapsort(int*, int);
void sift_up(int*, int);
void sift_down(int*, int);
void build_max_heap(int*, int);
void bottom_up_build_max_heap(int*, int);
void swap(int*, int*);
int heapsize;
int main() {
int A[] = { 7, 12, 1, -2, 0, 15, 4, 11, 9 };
int B[] = { 7, 12, 1, -2, 0, 15, 4, 11, 9 };
int i;
int size = 9;
printf("Unsorted array: \n");
for(i = 0; i < size; i++) {
printf(" %d ", A[i]);
}
heapsort(A, size);
printf("\n");
printf("Sorted array: \n");
for(i = 0; i < size; i++) {
printf(" %d ", A[i]);
}
printf("\n");
printf("----------------------------------\n");
printf("Unsorted array for bottom up: \n");
for(i = 0; i < size; i++) {
printf(" %d ", B[i]);
}
bottom_up_heapsort(B, size);
printf("\n");
printf("Sorted array: \n");
for(i = 0; i < size; i++) {
printf(" %d ", B[i]);
}
printf("\n");
return 0;
}
void bottom_up_heapsort(int* arr, int len) {
int i;
bottom_up_build_max_heap(arr, len);
for(i = len-1; i >= 1; i--) {
sift_up(arr, len);
heapsize--;
swap(&arr[i], &arr[0]);
}
}
void heapsort(int* arr, int len) {
int i;
build_max_heap(arr, len);
for(i = len-1; i >= 1; i--) {
swap(&arr[0], &arr[i]); // move arr[0] to its sorted place
heapsize = heapsize - 1;
sift_down(arr, 0); // repair the heap
}
}
void sift_down(int* arr, int i) {
int l = 2*i, r = 2*i+1;
int largest;
if(l < heapsize && arr[l] > arr[i]) {
largest = l;
}
else {
largest = i;
}
if(r < heapsize && arr[r] > arr[largest]) {
largest = r;
}
if(largest != i) {
swap(&arr[i], &arr[largest]);
sift_down(arr, largest);
}
}
void sift_up(int* arr, int i) {
if(i == 1) return; // at the root
if(arr[i] > arr[i/2]) {
swap(&arr[i], &arr[i/2]);
sift_up(arr, i/2);
}
}
void bottom_up_build_max_heap(int* arr, int len) {
heapsize = len;
int i;
for(i = 0; i <= len; i++) {
sift_up(arr, i);
}
}
void build_max_heap(int* arr, int len) {
heapsize = len;
int i;
for(i = len/2; i >= 0; i--) {
// invariant: arr[k], i < k <= n are roots of proper heaps
sift_down(arr, i);
}
}
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
You should be able to do
for (int i = 1; i <= n; i++) sift_up(heap, i);
which is equivalent to inserting the elements one by one. The worst-case running time is Theta(n log n), since in the worst case each new element must be sifted all the way to the root. This running time is worse than that of the sift_down heapify, namely, Theta(n). The difference is that sift_down can move the majority of elements only a couple levels down, while sift_up can move the majority of elements log n levels up.

bubble sort matrix with different col length

i need to do a bubble sort to matrix with different col lengths,
it need to be without the [] operand and in the language C.
i tried to do it like that :
for (i = 0; i < 5; i++)
{
first = (arr + i+d);// the first value in every line
for (j = 1; j <= (*first); j++)
{
for (d = 0; d <*(first)- j - 1; d++)
{
if (*(first+d+i) > *(first+d+1+i) )
{
swap =*(first+d);
*(first+d) = *(first+d+1);
*(first+d+1) = swap;
}
}
}
}
but it didn't work, someone can help me please ?
#include <stdio.h>
#include <stdlib.h>
typedef int Type;
#define PRN_Type "%d"
void print(Type **a, int size){
for(int i = 0;i<size;++i){
for(int j=1;j<=a[i][0];++j){
printf(PRN_Type " ", a[i][j]);
}
printf("\n");
}
}
void b_sort(Type **arr, int size){
int i, j, d;
Type swap, *first;
for (i = 0; i < size; ++i){
first = arr[i];//!!
for (j = 1; j <= *first; ++j){
for (d = 2; d <= *first -j+1; ++d){
if (*(first+d-1) > *(first+d) ){
swap =*(first+d-1);
*(first+d-1) = *(first+d);
*(first+d) = swap;
}
}
}
}
}
int main(void){
/*
int data[5][] = {
{3, 2,4,1},
{2, 99, 55},
{5, 9,5,1,7,5},
{1, 100},
{4, 5,5,5,5}
}
*/
int size = 5;
Type **data;
data = malloc(size * sizeof(Type*));
data[0]=(Type[]){3, 2,4,1};
data[1]=(Type[]){2, 99, 55};
data[2]=(Type[]){5, 9,5,1,7,5};
data[3]=(Type[]){1, 100};
data[4]=(Type[]){4, 5,5,5,5};
print(data, size);
b_sort(data, size);
printf("\n");
print(data, size);
return 0;
}

Resources