Comedy Hometown - Watch Comedy Hometown's Latest Video!

Welcome to Havenworld's Gaming, Computing and Programming Forums!

Unlock extra board access and remove this notice by registering for free below:
Choose username: Email:
Choose password: Antibot:
Type the letters shown in the picture to the left:
Verify password:

Pages: [1]   Go Down
  Print  
Author Topic: C - Exchange Sort Algorithm (My first C App)  (Read 401 times)
Project Evolution
Elitist Jerk of SMF
Ex-Staff
Havenworld Inhabitant
****

Reputation: 13
Offline Offline

Posts: 618


WWW
« on: March 21, 2010, 04:44:29 am »


My first program in C. It has been a learning process and I am actually quite confident with this language as a beginner. More to come.  8)

Code: [Select]
/*
 * File:   ExchangeSort.c
 * Author: Anthony Calandra
 *
 * Created on March 20, 2010, 5:22 PM
 */

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

/*
 * Append an array of 10 random integers, sort them in order using
 * the Exchange Sort algorithm
 */
main() {
    int arr[MAX_SIZE], i, j;
    printf("Creating array of 10 integers, appending random values: \n");
    for (i=0; i < MAX_SIZE; i++) {
        arr[i] = rand();
        printf(" %d", arr[i]);
    }
    printf("\n\n");
    printf("Sorting...\n");
    for (i=0; i < MAX_SIZE; i++)
        for (j=0; j < MAX_SIZE-1; j++) {
            if (arr[j] > arr[i]) {
                arr[i] ^= arr[j];
                arr[j] ^= arr[i];
                arr[i] ^= arr[j];
            }
        }
    for (i=0; i < MAX_SIZE; i++)
        printf(" %d ", arr[i]);
}

If people want these algorithms in Java I have no problem converting.

Basically we take the numbers present in the array, and loop through these numbers (i), then we loop through them length-1 times (j) and if j happens to be bigger than i, we swap the values and continue all the way through the array until all nmbers are in order. The reason we loop length-1 times is because there is always 1 number that doesnt need to be counted since either way it will be sorted.
Matt
Administrator
Havenworld Junkie
*

Reputation: 59
Offline Offline

Posts: 2024


« Reply #1 on: March 21, 2010, 08:58:15 am »

This is good, especially in C. I have problems printing strings lol.
Project Evolution
Elitist Jerk of SMF
Ex-Staff
Havenworld Inhabitant
****

Reputation: 13
Offline Offline

Posts: 618


WWW
« Reply #2 on: March 21, 2010, 04:01:20 pm »

Lol, I always forget having to use the reference operator (&) before my variables in scanf() so I guess you know what happens next... :$
hosting
First Poster
*

Reputation: 0
Offline Offline

Posts: 1


WWW
« Reply #3 on: May 17, 2010, 05:05:13 am »

thank you
Pages: [1]   Go Up
  Print  
 
 

Powered by SMF 1.1.6 | SMF © 2006-2008, Simple Machines LLC | Havenworld © 2006 - 2009 Havenworld Plc | The Peoples World
Page created in 0.135 seconds.