Sorting Arrays by even and odd numbers

Hello, I am tasked to complete several things in a project. I have some of it figured out but I am struggling with completing it. Here is the full set of instructions. Please, pardon my incompetence as I do not have much experience with programming yet.

Create a file with 20 integer numbers (10 pts)
Read the file into an integer array (20 points)
Split the array by: (30 points)
Placing all even numbers in one array
Place all odd numbers in another array
Use a selection sort function (will review in class) (30 points)
arrange the even numbers in ascending order
arrange the odd numbers in descending order
Print out both arrays (10 points)


My code completes all of these tasks, but not in the right way. I do not know how to implement the actual array list in my text file into the function to sort and I do not know how to separate the even and odd arrays. I am really struggling with polishing this code and I need some help, please!

[code]

#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#include <functional>
using namespace std;

//function to sort the even and odd numbers
//HELP - How do I separate this function to get two arrays?
void twoWaySort(int arr[], int n)
{
// Current indexes
int l = 0, r = n - 1;

// Count of odd numbers
int k = 0;

while (l < r) {
// Find first odd number
while (arr[l] % 2 != 0) {
l++;
k++;
}

// Find first even number
while (arr[r] % 2 == 0 && l < r)
r--;

// Swap odd number
if (l < r)
swap(arr[l], arr[r]);
}

// Sort odd number in descending order
sort(arr, arr + k, greater<int>());

// Sort even number in ascending order
sort(arr + k, arr + n);
}


int main()

{

//This code outputs the text file which has numbers 1-20
cout << "This is the array before being sorted." << endl;
cout << "\n";
ifstream file("Text.txt");
if (file.is_open())
{

string myArray[20];
for (int i = 0; i < 20; ++i)
{
file >> myArray[i];
cout << myArray[i] << " ";

}
}

cout << endl;

cout << "\n" << "Now the array is sorted in odd/descending order and then even/ascending order." << "\n" << endl;
int arr[] = { 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int n = sizeof(arr) / sizeof(int);
twoWaySort(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";

system("pause");
}
Ok, this is basically what you've got already and the output for the file I created called Values.txt is;

4047 2128 132 71950 88008 3000 10317 22872 912338 778042
933072 667182 284 940007 791 210846 31707 942283 1772316 118080
My code completes all of these tasks. Actually, your code doesn't complete any of the tasks, so a good start would be to create your text file of the values above, or any 20 values for that matter and we can proceed from there.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>

using namespace std;

int main (void) {
    int    myArray [20] {0};
    short pntr {0};
    
    // Control codes are VT100 compatible terminals on LINUX
    cout << "\033[2J\033[4;16HContents of Values.txt\n\n\t";
    ifstream data("Values.txt");
    
    if (data.is_open ()) {
        
        do {
            if (pntr == 10)
                cout << "\n\t";        // Do a newline 
                
            data >> myArray[pntr];
            cout << myArray[pntr] << " ";
        } while (!data.eof() && ++pntr < 20);
        
        data.close ();

    // TODO: Sort odd from evens and then sort both of those arrays          

    } else
        cout << "Failed to open file" << endl;
    
    cout << "\033[24H";
    return EXIT_SUCCESS;
}
Last edited on
the quick way is to rewire your sort to sort off even (or odd, doesnt matter) first and THEN by value, by changing how you compare 2 values.

bool islessthan(int a, int b) //this is the idea, and I think its right, but I didnt test it, so check it / make sure its what you want.
{
if(a%2 && b%2) return a < b; //if both the same, do normal compare.
if(!a%2 && !b%2) return a < b;
if(a%2 && !b%2) return false; //not the same: sort by even or odd instead of normal.
return true;
}
pull all the values in one big array, sort by even/odd, split the array into 2 bits, done. Remember that when splitting the arrays, you should copy one of them in reverse order to satisfy the requirement.

that can be coded more efficiently, its explicit here so you understand.
Last edited on
Ok, I got that code transferred and my data is entered.
Last edited on
I spent all morning editing my code and I fixed a few things. Unfortunately, my output is still bugged and I can't seem to fix it. I have zeros in front of my output and I do not know how to get rid of them.


Here is my code:


//This program will take in a file with 20 numbers and sort it into an array.
//It will then organize the array into an odd and even array (ascending order).

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cstdio>

using namespace std;

int readData(int nums[]); //Reads the in file
void print(int num[]); //Prints the array

int oddArray(int nums[]); //Finds the odd numbers in the array
int evenArray(int nums[]); // Finds the even numbers in the array
void swap(int* xp, int* yp);

int main()
{
int nums[20] = { 0 };

readData(nums); //reads the in file and sorts the numbers into an array

cout << "The original array is: "; //Prints the array.
print(nums);
cout << endl;

cout << "All odd numbers in ascending order, 0s represent a place holder to stay within bounds: ";
oddArray(nums); //Pulls out the odd numbers and puts them in an array with a length of 20. 0s are used as place holders.
cout << endl;

cout << "All even numbers in ascending order, 0s represent a place holder to stay within bounds: ";
evenArray(nums); //Pulls out the even numbers and puts them in an array with a length of 20. 0s are used as place holders.
cout << endl;
}

int readData(int nums[])
{
string fileName;

int i = 0; //counter to keep track of how many numbers are actually read from file
int num;

cout << "Enter file name to read data from: " << endl;

getline(cin, fileName);
ifstream fin;
fin.open(fileName);

if (fin.fail()) //if the file can't be opened
{
cout << "Couldn't find the given file. Enter to exit the program!" << endl;
cin.get();
exit(EXIT_FAILURE);
}
else
{
while (!fin.eof() && i < 20)
{
fin >> nums[i];
i++;
}
}
fin.close();
return i; // return the number of elements in the array
}

void print(int nums[])
{
for (int i = 0; i < 20; i++)
cout << nums[i] << " ";
cout << endl;
}

int oddArray(int nums[])
{
int odd[20] = { 0 };

for (int i = 0; i < 20; i++)
{
if (nums[i] % 2 != 0)
{
odd[i] = nums[i];
}
else
{
odd[i] = 0;
}
}
int i, j, min_idx;
for (i = 0; i < 20 - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < 20; j++)
if (odd[j] < odd[min_idx])
{
min_idx = j;
}

// Swap the found minimum element with the first element
swap(&odd[min_idx], &odd[i]);
}
for (i = 0; i < 20; i++)
{
cout << odd[i] << " ";
}
cout << endl;
return 0;
}

int evenArray(int nums[])
{
int even[20] = { 0 };

for (int i = 0; i < 20; i++)
{
if (nums[i] % 2 == 0)
{
even[i] = nums[i];
}
else
{
even[i] = 0;
}
}
int i, j, min_idx;
for (i = 0; i < 20 - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < 20; j++)
if (even[j] < even[min_idx])
{
min_idx = j;
}

// Swap the found minimum element with the first element
swap(&even[min_idx], &even[i]);
}
for (i = 0; i < 20; i++)
{
cout << even[i] << " ";
}
cout << endl;

return 0;
}

void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
Very good attempt, so have a look at this and it will give you some insight on how you might change your app. Please enclose your code in tags in the future.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <fstream>

using namespace std;

int main (void) {
    int    oddArray [20], evenArray [20];
    short pntr {0}, oddPntr {0}, evenPntr {0};
    
    // Control codes are VT100 compatible terminals on LINUX        
    cout << "\033[2J\033[4;16HContents of Values.txt\n\n\t";
    cout << "Source: "; 
    
    ifstream data("Values.txt");
    
    if (data.is_open ()) {        
        do {
            int value;
            
            if (pntr == 10)
                cout << "\n\t\t";        // Do a newline 
                
            data >> value;
            cout << value << ", ";
                        
            if (value%2)
                oddArray[oddPntr++] = value;
            else
                evenArray[evenPntr++] = value;
                
        } while (!data.eof() && ++pntr < 20);        
        data.close ();
        
    cout << "\n\n\tEven: ";
    for (int x = 0; x < evenPntr; x++)
        cout << evenArray[x] << " ";
    cout << "\n\t Odd: ";
    for (int x = 0; x < oddPntr; x++)
        cout << oddArray[x] << " ";
    } else {     
        cout << "Failed to open file" << endl;
        return EXIT_FAILURE;
        }    
         
    cout << "\033[24H";
    return EXIT_SUCCESS;
}


Last edited on
The selection sort must be in a separate function though. How would I transfer the if statements in main to a function?
You wouldn't change the conditional, only what it does something like this.

1
2
3
4
5
    if (value % 2) {
       SelSort ( oddArray, oddPntr, value);
          oddPntr++;
    } else
        evenArray[evenPntr++] = value;

Here is where you'd do you're sorting. Notice how the pointer for that particular array needs to be updated above in line 3. Now all that has to be done is the same for evens and implement your selection sort inside SelSort.

1
2
3
void SelSort ( int array[], int offset, int value) {
    array [offset] = value;
}


Topic archived. No new replies allowed.