EEVblog Electronics Community Forum

Products => Computers => Programming => Topic started by: Kittu20 on January 18, 2023, 01:17:19 pm

Title: function to sort array
Post by: Kittu20 on January 18, 2023, 01:17:19 pm
Hi,
I have written code to sort array numbers in increasing order

Code: [Select]
 #include <stdio.h> 

int main()
{
   int i = 0;
   int j = 0;
   int temp;
   
   int array[5] = { 50, 40, 30, 20, 10}; 
   
   for ( i = 0; i < 5; i++)
   {
    for ( j = i + 1; j < 5; j++)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;   
}
   
   }
   
   for ( i = 0; i < 5; i++)
   {
   printf(" %d ", array[i]);
   }
   
   
 
    return 0;
}

Program output

Code: [Select]
  10  20  30  40  50 

I am now trying to make a function to sort array in increasing order

Code: [Select]
 #include <stdio.h> 

void foo ( int *ptr)
{
// How to sort array in increasing order in function

}

int main()
{
   int i = 0;
   int j = 0;
   int temp;
   
   int array[5] = { 50, 40, 30, 20, 10}; 
   
   foo(&array[0]);
   
   // print array after calling function
   for ( i = 0; i < 5; i++)
   {
   printf(" %d ", array[i]);
   }
   
 
    return 0;
}

I am looking help to make function so how to make function that sort array in increasing order
Title: Re: function to sort array
Post by: DiTBho on January 18, 2023, 02:01:40 pm
I think the simplest sorting algorithm is "Bubble Sort".
It works by repeatedly swapping the adjacent elements if they are in the wrong order.

Title: Re: function to sort array
Post by: Kittu20 on January 18, 2023, 05:30:12 pm
I think the simplest sorting algorithm is "Bubble Sort".
It works by repeatedly swapping the adjacent elements if they are in the wrong order.

I just want to do in a function what i did in main function. I can't figure out how to do it
Title: Re: function to sort array
Post by: DiTBho on January 18, 2023, 06:10:22 pm
Code: [Select]
void data_sort
(
    uint32_t my_data[],
    uint32_t my_size
)
{
    uint32_t i0;
    uint32_t i1;
    uint32_t val0;
    uint32_t val1;

    for (i0 = 0; i0 < my_size; i0++)
    {
        for (i1 = 0; i1 < my_size; i1++)
        {
            val0 = my_data[i0];
            val1 = my_data[i1];
            if (val0 <= val1)
            {
                my_data[i0] = val1;
                my_data[i1] = val0;
            }
        }
    }
}

void data_show
(
    uint32_t my_data[],
    uint32_t my_size,
    uint32_t width
)
{
    uint32_t i0;

    printf("{\n");
    for (i0 = 0; i0 < my_size; i0++)
    {
        if (((i0) remaind width)isEqualTo 0)
        {
            printf("    ");
        }
        printf("%05lu ", my_data[i0]);
        if (((i0 + 1) remaind width)isEqualTo 0)
        {
            printf("\n");
        }
    }
    if ((i0 remaind width)isNotEqualTo 0)
    {
        printf("\n");
    }
    printf("}\n");
}

int main()
{
    uint32_t my_data[] =
    {
        50,  40,  30,  20, 10,
        150, 340, 130, 2, 1,
        250, 440, 530, 9, 11,
    };
    uint32_t my_size = (sizeof(my_data) / sizeof(uint32_t));

    data_sort(my_data, my_size);
    data_show(my_data, my_size, 4);

    return 0;
}

Code: [Select]
{
    00001 00002 00009 00010
    00011 00020 00030 00040
    00050 00130 00150 00250
    00340 00440 00530
}

Something like this. Mind, there are things to be fixed and modified.
(the two for-loops can be optimized: your homework).

This source is similar to C, adapt it to C89.

Have fun  :D
Title: Re: function to sort array
Post by: TheCalligrapher on January 18, 2023, 06:55:45 pm
I have written code to sort array numbers in increasing order

No, you haven't. There's nothing in your code to impose any kind of specific order (increasing, decreasing or whatever) onto the array. Your code is simply doing a fancy shuffle.

Program output

Code: [Select]
  10  20  30  40  50 


No, this is just a coincidence. Take a different array and try again. Your code does not sort the array.
Title: Re: function to sort array
Post by: mwb1100 on January 18, 2023, 07:53:14 pm
I have written code to sort array numbers in increasing order
No, you haven't. There's nothing in your code to impose any kind of specific order (increasing, decreasing or whatever) onto the array. Your code is simply doing a fancy shuffle.

More specifically, it is reversing the array.
Title: Re: function to sort array
Post by: SiliconWizard on January 18, 2023, 08:49:56 pm
All those threads are absolutely not a succession of homework, are they? :horse:
Title: Re: function to sort array
Post by: TheCalligrapher on January 18, 2023, 08:55:23 pm
More specifically, it is reversing the array.

True, but if reversing were the OP's intent, they would probably opt to implement it in a much less convoluted fashion.

This looks like a shot at selection sort. But they forgot to turn it into a sort.
Title: Re: function to sort array
Post by: IanB on January 18, 2023, 08:56:11 pm
All those threads are absolutely not a succession of homework, are they? :horse:

Also, this thread seems to be heading in the direction of pointers, which is the rock on which many students will stumble.
Title: Re: function to sort array
Post by: t3 on January 18, 2023, 09:28:06 pm
https://en.wikipedia.org/wiki/Sorting_algorithm
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

I highly recommend finding all plain-text descriptions of different algorithms that you can and implementing them. Writing a shuffle function will be useful for testing.
Title: Re: function to sort array
Post by: SiliconWizard on January 18, 2023, 09:30:41 pm
More specifically, it is reversing the array.

True, but if reversing were the OP's intent, they would probably opt to implement it in a much less convoluted fashion.

This looks like a shot at selection sort. But they forgot to turn it into a sort.

Yes, it misses the condition on order.

But this thing is still O(n^2). Not very efficient for reversing an array, is it? :-DD
Title: Re: function to sort array
Post by: Kittu20 on January 18, 2023, 09:38:41 pm
All those threads are absolutely not a succession of homework, are they? :horse:
All those threads are absolutely not a succession of homework, are they? :horse:


Also, this thread seems to be heading in the direction of pointers, which is the rock on which many students will stumble.
 
I sorted the array first in main function,  I thought it would be nice to make a function. I use pointer to alter array from function. so now i don't understand how to complete the function.
Title: Re: function to sort array
Post by: gf on January 18, 2023, 10:08:47 pm
You can also use the function qsort() (https://en.cppreference.com/w/c/algorithm/qsort) from the C library.
Title: Re: function to sort array
Post by: MIS42N on January 22, 2023, 01:42:43 am
I sorted the array first in main function,  I thought it would be nice to make a function. I use pointer to alter array from function. so now i don't understand how to complete the function.
Are you sure you have read the replies? DiTBho wrote the function for you. You have to pass two pieces of information - what array is to be sorted, and how many elements.

Also, although you say you sorted the array, it was an accident. You didn't compare adjacent numbers to see if they needed swapping. It just happens the array you started with, and the method you use, always needs the elements to be swapped. Put the numbers at the start in any other order, they will not end up sorted. Again, look at DiTBho code which does have the compare.
Title: Re: function to sort array
Post by: DiTBho on January 22, 2023, 12:57:10 pm
Code: [Select]
void data_back
(
    uint32_t my_data[],
    uint32_t my_size
)
{
    uint32_t i0;
    uint32_t i1;
    uint32_t val0;
    uint32_t val1;

    i1 = (my_size - 1);
    for (i0 = 0; i0 < ((my_size + 1) / 2); i0++)
    {
        val0 = my_data[i0];
        val1 = my_data[i1];

        my_data[i0] = val1;
        my_data[i1] = val0;

        i1--;
    }
}

Code: [Select]
    uint32_t my_data[] =
    {
        'h', 'A', 'l', 'l', 'o',
    };
    uint32_t my_size = (sizeof(my_data) / sizeof(uint32_t));

Code: [Select]
{
    h A l l o
}
{
    o l l A h
}

reverse order  ;D
Title: Re: function to sort array
Post by: djsb on January 22, 2023, 01:17:42 pm
Why does nobody include comments in their code any more? It REALLY helps people like me who are trying to follow along. It also helps as a reminder when returning to the code later. Thanks.
Title: Re: function to sort array
Post by: magic on January 22, 2023, 01:42:37 pm
First of all, DiTBho should have used i and j as indices instead of i0 and i1 :-- ::) :rant:

Secondly, his sorting algorithm is inefficient and ridiculous (perhaps deliberately so to troll the OP) and I'm not sure if it could be easily explained with a few lines of comment. Maybe the author could prove me wrong ;)
Title: Re: function to sort array
Post by: DiTBho on January 22, 2023, 04:44:15 pm
First of all, DiTBho should have used i and j as indices instead of i0 and i1

I always index my loop-indices :D
Several reasons, include 'cause it makes easier to search among the code, even on a poor note-pad.

e.g.
Search within block of text for "i": what? pr*I*nt?
Search within block ot text for "i0": better, no collisions, rights to the goal.

Isn't this good? Sorry, but it's good for me  :D


Secondly, his sorting algorithm is inefficient and ridiculous (perhaps deliberately so to troll the OP) and I'm not sure if it could be easily explained with a few lines of comment. Maybe the author could prove me wrong ;)

Ummm, I wrote it that way 'cause it's the most intuitive, but I clearly said in my post that it's the worst implementation ever, indeed I concluded my post asking the OP to "re-think" the algorithm loops to make it more efficient.

You can do it, and post it.
Title: Re: function to sort array
Post by: DiTBho on January 22, 2023, 04:45:09 pm
(the two for-loops can be optimized: your homework).
Title: Re: function to sort array
Post by: magic on January 22, 2023, 05:20:40 pm
Several reasons, include 'cause it makes easier to search among the code, even on a poor note-pad.

e.g.
Search within block of text for "i": what? pr*I*nt?
Search within block ot text for "i0": better, no collisions, rights to the goal.
That's your punishment for not using vim :box:

As for the algorithm, I recognize it now. It think it's this recently popularized "I don't understand Insertion Sort" algorithm which we have discussed previously on the forum.
https://www.eevblog.com/forum/programming/interesting-new-sort-algorithm/msg4316548/#msg4316548 (https://www.eevblog.com/forum/programming/interesting-new-sort-algorithm/msg4316548/#msg4316548)
Title: Re: function to sort array
Post by: IanB on January 22, 2023, 06:31:19 pm
Why does nobody include comments in their code any more? It REALLY helps people like me who are trying to follow along. It also helps as a reminder when returning to the code later. Thanks.

Comments can make complex algorithms easier to understand. However, comments can also make the code "noisy" when the code itself is simple enough to understand by itself. There's a balance to be found. It also helps to follow standard patterns so that people can recognize what they see at a glance. Something like this, perhaps?

Code: [Select]
/* Reverse.c */

#include <stdio.h>

void reverse(int a[], int size);
void print(int a[], int size);

int main()
{
    int data[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 4 };
    int datalen = sizeof(data) / sizeof(data[0]);

    print(data, datalen);
    reverse(data, datalen);
    print(data, datalen);

    return 0;
}

void reverse(int a[], int size)
{
    /* reverses an array of integers in place */
    int i, j, tmp;

    for (i = 0, j = size - 1; i < j; ++i, --j) {
        tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}

void print(int a[], int size)
{
    /* prints a list of integers */
    int i;

    for (i = 0; i < size; ++i) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

Output:

Code: [Select]
3 1 4 1 5 9 2 6 5 4
4 5 6 2 9 5 1 4 1 3
Title: Re: function to sort array
Post by: brucehoult on January 22, 2023, 08:55:17 pm
Why does nobody include comments in their code any more? It REALLY helps people like me who are trying to follow along. It also helps as a reminder when returning to the code later. Thanks.

The very mostest fun is when the comments are wrong. e.g. "// sort the array" when you're actually reversing it.
Title: Re: function to sort array
Post by: SiliconWizard on January 22, 2023, 09:02:07 pm
Beyond the point about comments, that has been discussed in another thread lately already (so please let's not start it all over again here), it was rather likely that this thread was some homework, and people are already nice to give code snippets (I don't think they should) rather than just general pointers. So expecting them to comment their code snippets is frankly absurd IMHO. ::)
Title: Re: function to sort array
Post by: DiTBho on January 22, 2023, 09:15:50 pm
this recently popularized "I don't understand Insertion Sort" algorithm which we have discussed previously

Yeah, I remember people in this forum said it's the most intuitive, so I... I used that as an example. But, behing my decision, I thought that, despite it's good because it "just works",  one can immediately recognize that it sucks here and there, so so it's also offers a good goal for a beginner: to make it better  :D
Title: Re: function to sort array
Post by: magic on January 22, 2023, 09:37:46 pm
LOL, I was actually the one who I think argued the loudest that it is a trivial derivative of a known trivial algorithm :D

But I wouldn't exactly describe it as intuitive, because there is no sensible concept to it that I can see. Bubble Sort repeatedly scans the array and pushes the largest element to the end. Insertion Sort picks each element in turn and moves it backwards as far as it fits. The only way I can explain Idiot Sort is that it performs Insertion Sort as a subset of its operations and then the remaining operations don't screw up the work done by this Insertion Sort subset.

For beginners it is probably better to first learn algorithms that are designed to work in accordance with a clear principle of operation, then try to analyze random junk like Idiot Sort ;)