user3006517
user3006517

Reputation: 1

Manipulating an Array

I am new to C programming and I have an assignment that I am not even sure where to start. This is what I have to do: Take a List of integers and sort them into odds and evens putting the even integers to the back of the list in the order in which the occurred. And we have to return the number of even integers in the List[]

For example:

suppose the array list is initialized with Size set to 10:

int List[Size] = {13, 31, 24, 16, 3, 48, 21, 11, 39, 6};

Then a call to evensToBack() should result in

Index: 0 1 2 3 4 5 6 7 8 9

Value: 13 31 3 21 11 39 24 16 48 6 And the Value 4 being returned.

All with that all I am given is this starting piece of code:

`int evensToBack(int* const List, const int Size){
//body
}`

Please help explain to me how to get started here. I would greatly appreciate it.

Upvotes: 0

Views: 107

Answers (3)

DeMarco
DeMarco

Reputation: 599

You just have to make a loop through the array and place the even numbers in the last position.

Something like:

for(i=0;i<length(List);i++)
   if isEven(List[i]){
      tempvar=List[i];
      for(j=i;j<length(List)-1;j++) List[j]=List[j+1];
      List[j+1]=tempvar;
    } 

Upvotes: 1

qdev76
qdev76

Reputation: 149

Seems to me like you want to be given directions rather than the answer. With that in mind, here's the thought process when I look at these problems:

  1. In order to sort any list, you must go through the entire list at least once
  2. How are you going to determine if it's even or odd?
  3. What are you going to do with the number after you figure this out?
    • are you going to put the results into new lists?
    • are you going to modify the current list?
    • other possibilities

My Full Procedure

Upvotes: 1

JoeC
JoeC

Reputation: 1850

keeping track of 2 indices, top and bottom

so you will have top = 0 and bottom = Size - 1 at the beginning

loop through the list to set the bottom index (Just to make sure the bottom index is pointing at the most bottom odd number)

loop through the list again with top = 0

if List[top]%2 != 0 // if its an odd number
    swap it with List[bottom]
    decrement bottom by 1
increment top by 1

until Size > top or top == bottom

Note: you will need to create your own list since the parameters are all constants so you can't modify the list that is passed to the function

Upvotes: 0

Related Questions