sorting

sorting array in descending order

Page 1 of 1

1 Replies - 1522 Views - Last Post: 09 November 2007 - 09:47 AM Rate Topic: -----

#1 patins0202  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 04-November 07

sorting

Post icon  Posted 04 November 2007 - 11:41 AM

I am new to programming. I would like to sort an unknown number of integers in a descending order. I can't get the sorting part right...please help, this is my java code:

import java.io.*;
import java.util.*;


public class descending
{
public static void main(String args[])
{
int n=0,i,max=-1,low=0,mid=0,x=0;
int A[]=new int[n];
int count[]=new int[11];

int num[]=new int[x];
Scanner kb=new Scanner(System.in);

System.out.println("How many numbers would you like to sort?");
n=kb.nextInt();


for(i=1;i<=n;i++)

{

System.out.println("Please enter a number.");
x=kb.nextInt();
}
System.out.println("All numbers are entered");
{
if(count[max]<count[x])

max=x;
}
while(max==x)

mid=(low+max)/2;

if(A[mid]==x)

max=mid;

else if(A[mid]>x)

max=mid-1;

else

mid=mid+1;


System.out.println("Your numbers in sorted order are:"+max);
}
}

Is This A Good Question/Topic? 0
  • +

Replies To: sorting

#2 sadiq_computers  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-November 07

Re: sorting

Posted 09 November 2007 - 09:47 AM

You are not understanding some concepts,
1. Creating arrays with variable does not mean to create variable length arrays. For example if n value is 2 and you created array like
int a = new int[n];
it is equivalent to
int a = new int[2];
ie, if n value changes then array size does not changes. Instead use like this one,
int n = 0;
int[] a = null;
//read n
a = new int[n];

2. You are not storing the numbers anywhare.
for(i=1;i<=n;i++)
{

System.out.println("Please enter a number.");
x=kb.nextInt(); // x will be replaced each time u read a new number.
}

I think u r trying to sort using binary sort. U not mentioned the name so a simple method to sort decending may be,

import java.util.Scanner;

public class Decending 
{
	public static void main(String[] args) 
	{
		int n;
		int[] a = null;
		Scanner sc = new Scanner( System.in );

		System.out.print( "How many numbers you want to sort : " );
		n = sc.nextInt();

		a = new int[n];
		System.out.print( "Enter numbers : " );

		for ( int i=0; i<n; i++ )
			a[i] = sc.nextInt();

		for ( int i=0; i<n-1; i++ )
		{
			for ( int j=i+1; j<n; j++ )
			{
				if ( a[i] < a[j] )
				{
					int temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}
		
		System.out.print( "After sorting in decending order :" );
		for ( int i=0; i<n; i++ )
		{
			System.out.print( " " + a[i] );
		}
	}
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1