I already arrange non-negative numbers to the left side of the array, now I want to put the sort function to rearrange numbers in ascending order into my program but it didn’t work, I can’t have them both, can you all help please? I’m totally new to this.
int tg;
for(int i = 0; i < n - 1; i++){
for(int j = i + 1; j < n; j++){
if(a[i] > a[j]){
tg = a[i];
a[i] = a[j];
a[j] = tg;
}
}
}
#include<bits/stdc++.h>
using namespace std;
void segregateElements(int arr[], int n)
{
int temp[n];
int j = 0; // index of temp
for (int i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
if (j == n || j == 0)
return;
for (int i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
memcpy(arr, temp, sizeof(temp));
}
int main()
{
int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
segregateElements(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
*Output : 1 7 5 11 6 -1 -3 -2 *
Expected: 1 5 6 7 11 -1 -2 -3
>Solution :
First,a part of your code is this
int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
but,the output you want is
1 2 3 6 11 -1 -5 -7
You maybe make some mistakes : there is no -7 in the arr
I think the code below will solve your problem
#include<bits/stdc++.h>
using namespace std;
void segregateElements(int arr[], int n)
{
int temp[n];
int j = 0; // index of temp
for (int i = 0; i < n ; i++)
if (arr[i] >= 0 )
temp[j++] = arr[i];
if (j == 0 || j == 1)
return;
for(int i = 0;i < j;i++){
for (int k = 0;k < j - 1;k++){
if (temp[k+1]<temp[k]){
int tg = temp[k+1];
temp[k+1] = temp[k];
temp[k] = tg;
}
}
}
for (int i = 0 ; i < n ; i++)
if (arr[i] < 0)
temp[j++] = arr[i];
memcpy(arr, temp, sizeof(temp));
}
int main()
{
int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
segregateElements(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout <<endl;
return 0;
}