Looks like insertion, doesn't it?

What type of sort does the following function in C/C++ implement?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void sort(int *a,int len,int ord){
    int i,j;
    for(i=1;i<len;i++){
        for(j=i;j>0;j--){
            if((ord==1 && a[j]<a[j-1]) || (ord==2 && a[j]>a[j-1]))
                swap(&a[j],&a[j-1]);
            else
                break;
        }
    }
}

Details and Assumptions:

  • a is the int array to be sorted, or more precisely, it denotes the base address of the array to be sorted.
  • len is the length of the array a , i.e., the number of elements in the array to be sorted.
  • ord specifies the sorting order, where 1 is used for ascending sort and 2 is used for descending sort.
  • swap() is a function which swaps the values of two int variables via a call by reference. The explicit definition for this function is:
1
2
3
4
5
void swap(int *x,int *y) {
    int t=*x;
    *x=*y;
    *y=t;
}

Quick Sort Insertion Sort Merge Sort Bubble Sort Heap Sort Shell Sort Selection Sort None of these

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Hasmik Garyaka
Sep 17, 2017

You should not put break after else.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...