• Welcome to Valhalla Legends Archive.
 

Sorting arrays

Started by Falcon[anti-yL], February 01, 2005, 08:11 PM

Previous topic - Next topic

Falcon[anti-yL]

I'm supposed to create an array of 50 random integers between 1 and 100, then sort it using the dumb bubble sort. Printing the original list, the list after each pass, and the final sorted list. Here's my code

import java.lang.System;
import java.util.Random;

public class sort_2
{
public static void main(String []args)
{
Random r = new Random();
int x[] = new int[50];
int swaps = 0, passes = 0, temp;

for(int i=0;i<x.length;i++)
{
x[i] = r.nextInt(100) + 1;
}
System.out.print("Original Array \n[ ");
for(int i=0;i<x.length;i++)
{
System.out.print(x[i]+" ");
}
System.out.print("] \nSorted Array \n[ ");
for(int p=1;p<x.length;p++)
for(int i=0;i<x.length-1;i++)
{
if(x[i] > x[i+1])
{
temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
}
}
for(int a=0;a<x.length;a++)
{
System.out.print(x[a]+" ");
}
System.out.print("] \n");
}
}

That only prints the original and final sorted list, I thought it would print it after each pass if I put

for(int a=0;a<x.length;a++)
{
System.out.print(x[a]+" ");
}

after

if(x[i] > x[i+1])
{
temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
}

But when I compile and run it, it seems like an infinite loop. Can someone tell me where to put the output statement that'll print the list after each pass?

Kp

Perhaps you should refrain from resetting your iteration counter while it's still in use.  Use an int j for your printing code inside the sorting loop.
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

Falcon[anti-yL]

Ahh it works now, thanks :)