sleep sort in c++ 11

guys i am thinking about one sorting method,it is called sleep sort

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int c, char **v)
{
    while (--c > 1 && !fork());
    sleep(c = atoi(v[c]));
    printf("%d\n", c);
    wait(0);
    return 0;
}

i dont understand one thing,what is fork equivalent in c++ 11?i meant new version of c++?i could write wait function like this

void wait ( int seconds ){
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}
}

but what about fork()? i have try following code

#include<iostream>
#include<time.h>
using namespace std;;

void wait ( int seconds ){
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}
}

void Sort(int c,int a[])
{
    while(--c>1)
    {
        wait(c=a[c]);
        cout<<c<<"  ";
    }
 }

int main()
{
    int a[]={1, 3, 2, 11, 6, 4};
    int c=5;
    Sort(c,a);
    wait(0);

    return 0;
}

but it does not give me sorted output,it outputs like 6 4 1 and finishes,so please tell me how to correct it?

Answers


Here is a working implementation in C++ using Win32:

#include <windows.h>
#include <iostream>

using namespace std;

DWORD threadFunc(LPVOID param)
{
    long val = (long)param;
    Sleep((int)val * 1000);
    cout << val << " ";
    return 0;
}

int main()
{
    HANDLE handles[6];
    int arr[] = {1, 3, 2, 11, 6, 4};

    for(int i = 0; i < 6; i++)
    {
        handles[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&threadFunc, 
                                  (LPVOID)arr[i], 0, NULL);
    }

    WaitForMultipleObjects(6, handles, 1, INFINITE);
}

You cannot simply delay as in your wait() function; this works by creating a new process (via fork()) for each argument and letting each sleep in parallel; your proposal would have each element sleep in series, thus not giving the illusion of a sort.

As to what is fork equivalent in c++ 11? -- fork() is not specific to C or C++; it's an operating system provided function.


You've not understood the point. The waits must run in parallel (triggered by fork, which creates a new thread for each item).


Although there are more things to talk about, I'm only going to answer your main question.

You have set c=5 although you have 6 numbers, and you have while(--c>1) so, if you calculate, it only runs the loop 3 times, because if you add the -- before the operator it will first substract 1 and then compare.

  • c=5
  • while(--c>1) [substract 1 of 5=4 and check if is bigger than 1] //runs it
  • while(--c>1) [substract 1 of 4=3 and check if is bigger than 1] //runs it
  • while(--c>1) [substract 1 of 3=2 and check if is bigger than 1] //runs it
  • while(--c>1) [substract 1 of 2=1 and check if is bigger than 1] //doesn't run it

You have to change c to the quantity of numbers you have: c=6, then change the while loop like this: while(c-->0)


Need Your Help