# Selection sort

• 09-17-2011
newbie_l
Selection sort
i have two logics for selection sortind...pointer p is for arrays base address.
1st logic:

Code:

```void selectionSort(int *p) {   int i,j,temp;   for(i=0;i<24;i++)   {     for(j=1;j<25;j++)     {       if(*(p+i)>*(p+i+j))       {         temp=*(p+i);         *(p+i)=*(p+i+j);         *(P+i+j)=temp;       }   }  } }```
2nd logic:

Code:

```void selectionSort(int *p) {   int i,j,temp;   for(i=0;i<24;i++)   {     for(j=i+1;j<25;j++)     {       if(*(p+i)>*(p+j))       {         temp=*(p+i);         *(p+i)=*(p+j);         *(P+j)=temp;       }   }  } }```

My question is---logic 1 is not working correctly...i am not able to find out any error.....if anybody?????plzzz explain the fault
• 09-17-2011
quzah
Consider this:
Code:

```  for(i=0;i<24;i++)   {     for(j=1;j<25;j++)     {       if(*(p+i)>*(p+i+j))```
If p is the start of your array, and i is 20, and j is 20 ... p[40] is way off the end of your array.

Quzah.
• 09-17-2011
newbie_l
i got it....thnxxx a lot!
• 09-17-2011
CommonTater
Hard way...
Code:

```void selectionSort(int *p) {   int i,j,temp;   for(i=0;i<24;i++)   {     for(j=1;j<25;j++)     {       if(*(p+i)>*(p+i+j))       {         temp=*(p+i);         *(p+i)=*(p+i+j);         *(P+i+j)=temp;       }   }  } }```
Easy way....
Code:

```void selectionSort(int *p) {   int i,j,temp;   for(i=0;i<24;i++)   {     for(j=1;j<25;j++)     {       if(p[1] > p[j]))       {         temp= p[i];         p[i] = p[j]);         p[j] =temp;       }   }  } }```
• 09-17-2011
iMalc
None of those implementations posted are actually Selection Sort.
Onet of them is actually Bubble Sort, and the rest are just broken.
The inner loop of seletion sort does not perform a swap. It simply records the position of the lowest (or highest) item, then after that loop it swaps that item into position. Take a look at the implementation on Wikipedia.

The original code listed as "1st logic" does not work because in the expression *(p+i+j), i+j exceeds 24 and so is a buffer overrun. Not that the size should be hard-coded to 25 to begin with, of course.