So I am not sure why this is becoming so hard for me, but I need to sort high to low and low to high.
For high to low I have:
int a, b;
int temp;
int
Unless you think using already available sort functions and autoboxing is cheating:
Integer[] arr =
{ 12, 67, 1, 34, 9, 78, 6, 31 };
Arrays.sort(arr, new Comparator<Integer>()
{
@Override
public int compare(Integer x, Integer y)
{
return x - y;
}
});
System.out.println("low to high:" + Arrays.toString(arr));
Prints low to high:[1, 6, 9, 12, 31, 34, 67, 78]
if you need high to low change x-y to y-x in the comparator
Let me know if this works:
public class prog1 {
public static void main (String args[]){
int a[] = {1,22,5,16,7,9,12,16,18,30};
for(int b=0; b<=a.length;b++){
for(int c=0; c<=a.length-2;c++){
if(a[c]>a[c+1]){
int temp=0;
temp=a[c];
a[c]=a[c+1];
a[c+1]=temp;
}
}
}
for(int b=0;b<a.length;b++){
System.out.println(a[b]);
}
}
}
If you just want sort the int array: Use the quicksort... It's not a lot of code and it's N*lgN in avarage or N^2 in worst-case. To sort multiple data, use the Java Compare (as above) or a stable sorting algorithm
static void quicksort(int[] a,int l, int r){
if(r <= l) return;
int pivot = partition(a,l,r);
//Improvement, sort the smallest part first
if((pivot-l) < (r-pivot)){
quicksort(a,l,pivot-1);
quicksort(a,pivot+1,r);
}else{
quicksort(a,pivot+1,r);
quicksort(a,l,pivot-1);
}
}
static int partition(int[] a,int l,int r){
int i = l-1;
int j = r;
int v = a[r];
while(true){
while(less(a[++i],v)); //-> until bigger
while((less(v,a[--j]) && (j != i))); //-> until smaller and not end
if(i >= j){
break;
}
exch(a,i,j);
}
exch(a,i,r);
return i;
}
You can try with bubble sort: Example shown below
int[] numbers = { 4, 7, 20, 2, 56 };
int temp;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j + 1])
{
temp = numbers [j + 1];
numbers [j + 1]= numbers [i];
numbers [i] = temp;
}
}
}
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i].toString());
}
You are never visiting the last element of the array.
Also, you should be aware that bubble sort is pretty inefficent and you could just use Arrays.sort().
You just need to write one string Arrays.sort(arr) for low to high for Java 8.
Arrays.sort(arr, Collections.reverseOrder()) for high to low