Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following program displays a list of numbers, then sorts them. There are two

ID: 3665524 • Letter: T

Question

The following program displays a list of numbers, then sorts them. There are two lists of numbers given, one sorted by insertion, one by bubblesort. I keep recieving segmentation error after sorting the first set of numbers, Can someone find the source of the error (or any others you might notice)

Thanks in advance.

Code:

#include
#include "sortings.h"
using namespace std;

void sortings::InsertionSort(){
bool done;
for (int i=1; i int position=i;
done=false;
while ((position>=1)&&(!done)){
if(intArray[position] < intArray[position-1]){
int temp;
temp = intArray[position-1];
intArray[position-1] = intArray[position];
intArray[position] = temp;
position--;
}
else
done=true;
}
}
}

void sortings::BubbleSort(){
int temp;
for (int i=1; i for (int position=0; position if (intArray[position] > intArray[position+1]){
int temp;
temp=intArray[position+1];
intArray[position+1]=intArray[position];
intArray[position] = temp;
}
}
}
}

void sortings::print(){
for(int k=0; k < size-1; k++){
cout << intArray[k] << endl;
k++;
}
}

sortings::sortings(){
capacity = INITIAL_CAPACITY;
int *intArray = new int[capacity];
size=0;
}

sortings::sortings(int in_capacity){
capacity=in_capacity;
int *intArray = new int[capacity];
size=0;
}

int sortings::getSize(){
return size; //returns size of inputs to be sorted
}

void sortings::insert(int item){
intArray[size]=item;
size++;
}


sortings::~sortings(){

}

Outputs:

The sequence of integers from FILE lab3_1.txt before sorting:
34
29
-45
999
34
57
2
7
10
5
2
5
2
-56
87
-99
299
The sequence of integers after sorting:
-99
-45
2
5
7
29
34
87
The sequence of integers from FILE lab3_2.txt before sorting:
Segmentation fault (core dumped)

Explanation / Answer

Normally this error "Segmentation fault (core dumped)" comes when we are trying to access memory which is not avaiable. It may arise by vague pointer.

So in insertion sort method you defined .. we are starting index from i=1, that means from starting. but inside function you are decrementing i--.. counter

void sortings::InsertionSort(){
bool done;
for (int i=1; i int position=i;
done=false;
while ((position>=1)&&(!done)){
if(intArray[position] < intArray[position-1]){
int temp;
temp = intArray[position-1];
intArray[position-1] = intArray[position];
intArray[position] = temp;
position--;
}
else
done=true;
}
}

So i cannot run this code since i dont have header file. But it might helpful to you. Better to debug line by line to get exact error line.