Sort an array of 100 numbers so that there is an alternation of negative and positive elements of the array (C ++) If not difficult, then with comment lines.
2 answers
In general, came up with 3 options. We work with the usual int array.
Option 1. The simplest, with the creation of a temporary array and back it up to the original array
void put_mem (int* vec, size_t ss) { int temp [ss]; for (int i = 0, pi = 0, ni = 1; i < ss; i++) { if (vec[i] >=0) {temp[pi] = vec[i]; pi +=2;} else {temp [ni] = vec[i]; ni +=2;} } memcpy (vec, temp, sizeof(int)*ss); }
Option 2. With work directly in an array like bubble sorting. Introduced an additional helper function swapp for exchanging values between array members. The algorithm is stupid and direct without optimization.
static inline void swapp (int& a1, int& a2) { int temp = a1; a1 = a2; a2 = temp; } void put_sw (int* vec, size_t ss) { size_t j; for (size_t i = 0; i < ss; i++) { if (vec[i] < 0) { j = i; while (vec[++j] < 0); swapp (vec[i], vec[j]); } i++; if (vec[i] >= 0) { j = i; while (vec[++j] >= 0); swapp (vec[i], vec[j]); } } }
Option 3. The most sophisticated, with the use of STL. But it will work only with arrays whose size is not divisible by 4.
void put_stl (int* vec, size_t ss) { int* it = partition (vec, vec+ss, bind2nd (less<int>(), 0)); for (int* itt = vec; it < vec+ss; it+=2, itt+=2) {swap (*itt, *it);} }
In this code, if there are more negative or positive numbers, then they are simply added to the end, but what else? Do not discard them =)
#include<iostream> using namespace std; void print_r(int *mass, int size) { for (unsigned i = 1; i <= size; i++) cout << mass[i] << ", "; cout << endl; } int main() { int mass[100]; for (unsigned i = 1; i <= 100; i++) mass[i] = rand() % 100 - 50; print_r(mass, 100); int h_m[100]; int s_m[100]; int c = 0; int c2 = 0; for (int i = 1; i <= 100; i++) { if (mass[i] < 0) { c2++; s_m[c2] = mass[i]; } if (mass[i] > 0) { c++; h_m[c] = mass[i]; } } cout << endl; print_r(h_m, c); cout << endl; print_r(s_m, c2); cout << endl; int new_mass[100]; int min = 0; if (c > c2) min = c2; else min = c; for (int i = 1; i <= min; i++) cout << s_m[i] << " " << h_m[i] << " "; if (min == c) for (int i = min + 1; i <= c2; i++) cout << s_m[i] << " "; if (min == c2) for (int i = min + 1; i <= c2; i++) cout << h_m[i] << " "; system("Pause"); }
If the negative and positive elements are equally, then they can simply be displayed in a cycle from 1 to 50 alternately.
2 + 2*0 vs n - 1* (2*0)
, 2 + 2 * 1 vs n - (1 + 2 * 1), 2 + 2 * 2 vs n - (1 + 2 * 2) ... `if you just need sorting with ignoring the value, then compare the absolute values of the numbers (take sorting, for example, with a bubble on the wiki, and add elements of abs (value) when comparing the elements, - or whatever you have in C :)) - jmu