Thread: reversing elements of an array

  1. #1
    Unregistered
    Guest

    reversing elements of an array

    heres my source code i dont know what im doing wrong.. to reverse the elements of the array so that a[0]=a[5],and a[1]=a[4]and so on......

    ex. a[]=8,9,13,3,2
    it now should be..... a[]=2,3,13,9,8

    my source code is below...help if u can...

    # include <stdio.h>

    # define MAX 6

    void insertionsort (int list[],int first,int last);

    int main (void)
    {
    int i;
    int ary[MAX]={89,72,3,8,25,6};

    printf("elements");
    for (i=0;i<MAX;i++)
    printf("%3d\n",ary[i]);

    insertionsort (ary,i,MAX);

    printf("elements reversed");
    for (i=0;i<MAX;i++)
    printf("%3d",ary[i]);

    return 0;
    }

    void insertionsort (int list[],int first,int last)
    {

    int temp;
    int end;
    int mid;

    mid=(first+last)/2;

    for (first=0;first<=mid;first++)
    for (end=last;end>mid;end--)
    if((first+last)==MAX)
    {
    temp=list[first];
    list[first]=list[last];
    list[last]=temp;
    }
    return;
    }

  2. #2
    l'Anziano DavidP's Avatar
    Join Date
    Aug 2001
    Location
    Plano, Texas, United States
    Posts
    2,743
    well, all you are doing is sorting the, not reversing them. so the array looks like this after the sort:

    3,8,6,25,72,89

    when it should look like this:

    6,25,8,3,72,89

    if you are going to reverse the order of the array, have a index variable for the end and the beginning, and then switch the two array indexes, then move the index variables by one, switch the array indexes, and so forth...
    My Website

    "Circular logic is good because it is."

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    z = (sizeof(array)/sizeof(int));
    for( y = 0,  x = (z-1); y < (z/2); y++, x-- )
    {
    	temp = array[x];
    	array[x] = array[y];
    	array[y] = temp;
    }
    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Unregistered
    Guest

    Talking thanx

    thanx ..you guys finnally helped me figure it out....damn ive been streesin over this for a week.. thanx

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. count elements in an array
    By whichet in forum C Programming
    Replies: 9
    Last Post: 11-25-2007, 08:05 AM
  2. Setting all elements of an array to zero
    By kolistivra in forum C Programming
    Replies: 9
    Last Post: 08-29-2006, 02:42 PM
  3. funtion dealing with positive array elements
    By dantestwin in forum C++ Programming
    Replies: 5
    Last Post: 07-08-2004, 05:20 PM
  4. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  5. Reversing a Multi-D Array
    By Bradley33 in forum C++ Programming
    Replies: 1
    Last Post: 11-19-2001, 11:37 AM