Troubleshooting a Segmentation Fault in a Selection Sort

Click For Summary
SUMMARY

The forum discussion addresses a segmentation fault encountered in a C implementation of the selection sort algorithm. The primary issue identified is the incorrect usage of the scanf function, which should use &arr[i] instead of arr[i] to correctly pass the address of the array element. Additionally, the loop conditions are incorrect; they should iterate up to 9 for the outer loop and 10 for the inner loop. It is also noted that the provided sorting algorithm resembles a bubble sort rather than a selection sort.

PREREQUISITES
  • Understanding of C programming syntax and semantics
  • Familiarity with array manipulation in C
  • Knowledge of sorting algorithms, specifically selection sort and bubble sort
  • Experience with debugging segmentation faults in C
NEXT STEPS
  • Review the correct usage of scanf in C
  • Learn about the differences between selection sort and bubble sort algorithms
  • Investigate common causes of segmentation faults in C programming
  • Implement a correct version of the selection sort algorithm in C
USEFUL FOR

C programmers, software developers, and students learning about sorting algorithms and debugging techniques in C.

george2625
Messages
3
Reaction score
0
please help me with a c code for the merge sort... and i am getting a segmentation fault in running this selection sort,,, please help...

#include <stdio.h>

int main( )
{
int arr[10];
int i,j,temp;
for ( i = 0 ; i<10 ; i++ )
{
printf("enter the numbers: \n");
scanf("%d \n", arr);
}
for ( i = 0 ; i <8 ; i++ )
{
for ( j = i + 1 ; j <9 ; j++ )
{
if ( arr > arr[j] )
{
temp = arr ;
arr = arr[j] ;
arr[j] = temp ;
}
}
}
for ( i = 0 ; i <10 ; i++ )
printf("the sorted array is: %d \n", &arr);
return 0;
}
 
Technology news on Phys.org


george2625 said:
please help me with a c code for the merge sort... and i am getting a segmentation fault in running this selection sort,,, please help...

scanf("%d \n", arr);

The problem is in your scanf statement. Scanf needs a reference and "arr" is already de-referenced. You need to prefix it with "&".
 
You probably wanted those loops to be ... ; i < 9; ... and ... ; j < 10; .... Also this algorithm is not a merge sort, it's a bubble (down) sort.
 

Similar threads

  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 29 ·
Replies
29
Views
4K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K