Click here to Skip to main content
15,868,292 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
You have been given an integer array A of size N. Each element of the array ranges between 1 and 10^5. You need to find the frequency of each distinct element of the array. The elements need to be present in the output in ascending order. You need to print the value and then frequency of each distinct element.
->I am getting this error
  Command failed: ./a.out <input2.txt
Segmentation fault


What I have tried:

C++
#include <iostream>
using namespace std;

void InsertionSort(int *arr,int n){
  int key,j=0;
  for(int i=1;i<n;i++){
    key = arr[i];
    j = i-1;
    while(j>=0 && key <arr[j]){
      arr[j+1] = arr[j];
      j = j-1;
    }
    arr[j+1] = key;
  }
}

void FrequencyAndPrint(int *arr,int n){
  int temp;
  int freq ;
  int j=0;
  for(int i=0;i<n;i++){
    temp = arr[i];
    freq = 1;
    for( j=i+1;j<n;j++){
      if(temp == arr[j])
      ++freq;
      else 
        break;
    }
    i = j-1;
    cout<<arr[i]<<" "<<freq<<endl;
  }
  return;
}

int main()
{
	int N;
  int arr[10];
  cin>>N;
  for(int i=0;i<N;i++){
    cin>>arr[i];
  }
  InsertionSort(arr,N);
  FrequencyAndPrint(arr,N);

	return 0;
}
Posted
Updated 5-Sep-18 22:34pm
v2
Comments
Mohibur Rashid 5-Sep-18 21:05pm    
have you tried to do debugging? Your integer is fixed length; If your N>10 you will get segmentation fault will occur. And if you are trying to implement insertion sort, you are doing it wrong.

With insertion short you sort while you insert. i.e. when your for loop is reading, you do the sort
gogobaba 5-Sep-18 22:07pm    
yes I have tried debugging.Can u please elaborate Why Insertion sort is wrong in this situation.
CHill60 6-Sep-18 4:03am    
Mohibur Rashid will not know you have responded to their comment because you have not used the "Reply" link

1 solution

You are using a fixed array, so if N is greater than 10 the result will most likely be a SEGV fault. You should allocate the array with the new statement after you have first accepted the value of N. Something like:
C++
int N;

cin >> N;
int* arr = new int[N];
for(int i=0; i < N; i++)
{
    cin >> arr[i];
}

You also need to check the contents of your input file to make sure it contains valid data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900