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 sortTheNumbers = len - 1;
for (a = 0; a < sortTheNumbers; ++a) {
for (b = 0; b < sortTheNumbers; ++b) {
if (array[b] < array[b + 1]) {
temp = array[b];
array[b] = array[b + 1];
array[b + 1] = temp;
}
}
}
However, I can't for the life of me get it to work in reverse (low to high), I have thought the logic through and it always returns 0's for all the values.
Any help appreciated!
The bigger picture is that I have a JTable with 4 columns, each column with entries of numbers, names, or dates. I need to be able to sort those back and forth.
Thanks!
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
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().
public class sorting {
public static void main(String arg[])throws Exception{
int j[]={1,28,3,4,2}; //declaring array with disordered values
for(int s=0;s<=j.length-1;s++){
for(int k=0;k<=j.length-2;k++){
if(j[k]>j[k+1]){ //comparing array values
int temp=0;
temp=j[k]; //storing value of array in temp variable
j[k]=j[k+1]; //swaping values
j[k+1]=temp; //now storing temp value in array
} //end if block
} // end inner loop
}
//end outer loop
for(int s=0;s<=j.length-1;s++){
System.out.println(j[s]); //retrieving values of array in ascending order
}
}
}
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
The only thing you need to do to change the sort order is change
if (array[b] < array[b + 1])
to
if (array[b] > array[b + 1])
Although, as others have noted, it's very inefficient! :-)
In java8 you can do something like this:
temp.stream()
.sorted((e1, e2) -> Integer.compare(e2, e1))
.forEach(e -> System.out.println(e));
You need a more efficient sort. like mergesort. try www.geekviewpoint.com and go to sort
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;
}
If you want to apply same logic as what you have done...by not using Arrays.sort...then following will help
int[] intArr = {5, 4, 3, 8, 9, 11, 3, 2, 9, 8, 7, 1, 22, 15, 67, 4, 17, 54};
//Low to high
for(int j=0; j<intArr.length-1; j++){
for(int i=0; i<intArr.length-1; i++){
if (intArr[i] > intArr[i+1]){
int temp = intArr[i+1];
intArr[i+1] = intArr[i];
intArr[i] = temp;
}
}
}
//High to low
for(int j=0; j<intArr.length-1; j++){
for(int i=0; i<intArr.length-1; i++){
if (intArr[i] < intArr[i+1]){
int temp = intArr[i+1];
intArr[i+1] = intArr[i];
intArr[i] = temp;
}
}
}
for(int ars : intArr){
System.out.print(ars+",");
}
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]);
}
}
}
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());
}
Related
I am trying to write a selection sort where I find the maximum in the (sub)array bounded by the int upper, and swap the current value with the max.
I have written three separate methods—I have a method for finding the index of the maximum value in the array, a method for swapping two values, and a sort method for actual sorting. I've tried debugging but am not very good at it...
public static void sort(Comparable[] array)
{
int maxindex = 0;
for(int k=0; k<array.length; k++)
{
maxindex = findMax(array, array.length-k);
if(maxindex < k)
swap(array, k, maxindex);
}
}
public static int findMax(Comparable[] array, int upper)
{ //"upper" controls where the inner loop of the selection sort ends
Comparable max = array[0];
int maxindex = 0;
for(int i = 1; i<upper; i++)
{
if(max.compareTo(array[i])<0)
{
max = array[i];
maxindex = i;
}
}
return maxindex;
}
public static void swap(Object[] array, int a, int b)
{
Object save = array[b];
array[b] = array[a];
array[a] = save;
}
I generate a random array and call the sort and print out the "sorted" array, except that the printed array is not sorted at all...
I took your code and made some modifications in sort as well as findMax function. Now, we are getting correct output.
sort function: I'm not sure why you have condition before the swap, it will prevent some of the findMax from swapping. Also, my guess is you are doing array.length - k because you might want to keep the maximum in the last index and loop through to find next maximum and so on. To do that your logic seems to be wrong.
findMax function: Index should start at 0 and go till upper.
See the below code for details:
public static void sort(int[] array) {
int maxindex = 0;
for(int k=array.length - 1; k >= 0; k--) {
maxindex = findMax(array, k);
swap(array, k, maxindex);
}
}
public static int findMax(int[] array, int upper) {
//"upper" controls where the inner loop of the selection sort ends
int max = array[0];
int maxindex = 0;
for(int i = 0; i <= upper; i++) {
if(max < array[i]) {
max = array[i];
maxindex = i;
}
}
return maxindex;
}
Input: [4, 2, 3, 8, 7, 1, 9, 10, 15, 12, 11, 13]
Output: [1, 2, 3, 4, 7, 8, 9, 10, 11, 12, 13, 15]
Since comparable is a raw type. References to generic type Comparable should be parameterised. Not recommended to use raw datatype, unless it is necessary.
The below program has few modifications done from your code. You can compare and it runs on O(n^2) complexity.
The main issue in your code is in findMax() function, the function is made static by hardcoding the value.
import java.util.Arrays;
public class XYZ {
public static void main(String args[]) {
sort(new Integer[] { 1, 5, 2, 11, 4 });
}
public static void sort(Comparable[] array) {
int maxindex = 0;
for (int k = 0; k < array.length; k++) {
maxindex = findMax(array, k);
if (maxindex > k)
swap(array, k, maxindex);
// System.out.println(Arrays.toString(array));
}
}
public static int findMax(Comparable[] array, int startIndex) {
Comparable max = array[startIndex];
int maxindex = 0;
for (int i = startIndex; i < array.length; i++) {
if (max.compareTo(array[i]) < 0) {
max = array[i];
maxindex = i;
}
}
return maxindex;
}
public static void swap(Object[] array, int a, int b) {
Object save = array[b];
array[b] = array[a];
array[a] = save;
}
}
I want to sort an array of int from the smallest value to the greatest one. I have created the next algorithm but the problem is that the new array does't receive the right values from the if statement. I am going put my code bellow.
public static void main(String[] args) {
int[] arr = {33,44,22,11,22,11};
int[] arrSort = new int[6];
int temp=0;
for (int i = 0; i < arrSort.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i + 1];
arr[i + 1] = arr[i];
arrSort[i] = temp;
}
else {
arrSort[i] = arr[i];
}
}
System.out.println(Arrays.toString(arrSort));
}
If i run the code I get the next values: [33, 22, 11, 22, 11, 0];
I just want to figure out what part of the algorithm was thought wrong. Thank you in advance.
You need to apply 2 loops.
1st loop is to access 1st arr element.
2nd loop is to access next(1st + 1)th element.
After comparing 1st element with other swap it accordingly.
public static void main(String []args)
{
int[] arr = {33,44,22,11,22,11};
int len=arr.length;
int temp=0,i,j;
for (i = 0; i < len; i++)
{
for (j = i+1; j < len; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
}
when it is the case of array Loops are very handy to use.
int[] yourArary = new int[10];
ArrayList<Integer> intArray = new ArrayList<>();
for( int value : yourArary ){
intArray.add( value );
}
Arrays.sort(intArray);
System.out.println(Arrays.toString(yourArary));
// you can short like this in reverse order
for (int i = yourArary.length - 1; i >= 0; i--)
System.out.print(yourArary[i] + " ");
System.out.println();
You cannot do it with just one loop. Sorting is a more complex than that. For bubble sort or selection sort it's like O(n^2). There are better algorithms that like quick sort or merge sort that have better results and aim for O(n log N) complexity. But anyway you can do it like that for example for a simple bubble sort implementation:
int[] arr = {33,44,22,11,22,11};
for (int i = 0; i < arrSort.length - 1; i++) {
for(int j=i;j<arrSort.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[j];
arr[j] = arr[i];
arr[i]=temp;
}
}
System.out.println(Arrays.toString(arr));
Don't know if this will help you, but why sort it by yourself, if Java can do the Job:
int[] unsortedArray = { 33, 44, 22, 11, 22, 11 };
ArrayList<Integer> intArray = new ArrayList<>();
for( int value : unsortedArray )
{
intArray.add( value );
}
Collections.sort( intArray );
System.out.println( intArray );
If you use the helper variable temp to move positions, you don't need a second array, just put it back into arr[i]. Second, one run is not enough, you will need to run this, until there are no position changes needed. So it would look like this:
public static void main(String[] args) {
//source Array
int[] arr = {33,44,22,11,22,11};
int temp=0;
//marker, that positions were switched
boolean sthChanged = false;
do
{
//in each run assume that nothing is left to change
sthChanged = false;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
//we found an instance, where the earlier position holds a higher int than the latter
//save the latter value in the temp variable
temp = arr[i + 1];
//move the former value to the latter position
arr[i + 1] = arr[i];
//fill the former position with the value from the temp variable
arr[i] = temp;
//set the marker to true, as there might be other changes to be done
sthChanged = true;
}
}
}
while (sthChanged); //stop only, if we didn't find sth to be changed in the last run
System.out.println(Arrays.toString(arr));
}
Best regards
First of all, u shud not use two arrays in your algorithm, as its just a waste of memory and unecessary array access overhead. If u need to retain the original array copy it over, and send the copied array to the sort method.
Secondly, for the method adopted here (bubble sort), you are iterating the array and finding the largest element and shifting it to the end.
U need to repeat this process, for each subarray of length-1, length-2 ... 1.
So the time complexity of this approach would be O(n^2). There are better algorithms, like MergeSort, QuickSort which can do the sort in the theoretical O(n log(n)) time.
See below the correctin required for your code :
public static void main(String[] args) {
int[] arr = {33,44,22,11,22,11};
//int[] arrSort = new int[6];
int temp=0;
for(int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
I am given k sorted arrays and need to merge them into one sorted array. We are assuming that n is the total number of elements in all the input arrays and that k=3.
public class Merge {
// Create a mergeklists() to merge 3 sorted arrays into one sorted array
// Input: 3 sorted arrays a1[], a2[], a3[]
// Output: one sorted array a[] that contains all the elements from input arrays
public static void merge3lists(int[] a1, int[] a2, int[] a3, int[] a)
{
int i=0;
int j=0;
int h=0;
int n = a1.length + a2.length + a3.length;
for(int k; a.length < n-1; k++){
if(a1[i] < a2[j]){
k = a1[i];
i++;
}
else if(a2[j] < a3[h]){
k = a2[j];
j++;
}
else{
k = a3[h];
h++;
}
}
}
public static void main(String[] args) {
int[] l1 = {1,5,9,10,20};
int[] l2 = {2,4,5,6,7,9,15};
int[] l3 = {3,8,13,15,22};
int[] newl = new int[l1.length+l2.length+l3.length];
merge3lists(l1,l2,l3,newl);
for(int i = 0; i< newl.length; i++)
{
System.out.print(newl[i]+ " ");
}
}
}
I know that the integers I am using (I,j,and h) are messing up the problem, but I don't think I can use i while comparing all the arrays. I need to use the declared array a, but I'm not sure how to reference it in this case.
To have to method merge an arbitrary number of arrays (k), you need to make the method use varargs.
It would also be better to have the method create the result array for you.
You then loop until the result array is filled. For each iteration, you find the smallest of the next value from each source array, and add that to the result array, and step forward in the source array you picked the value from.
Like this:
public static int[] mergeArrays(int[]... arrays) {
// Create result array
int n = 0;
for (int[] a : arrays)
n += a.length;
int[] result = new int[n];
// Start at index 0 in each source array
int[] idx = new int[arrays.length];
// Merge source arrays into result array
for (int i = 0; i < n; i++) {
// Find smallest value
int minJ = -1, minVal = 0;
for (int j = 0; j < arrays.length; j++) {
if (idx[j] < arrays[j].length) {
int val = arrays[j][idx[j]];
if (minJ == -1 || val < minVal) {
minJ = j;
minVal = val;
}
}
}
// Add to result array and step forward in appropriate source array
result[i] = minVal;
idx[minJ]++;
}
return result;
}
Test
int[] merged = mergeArrays(new int[] { 23, 39, 63, 68 },
new int[] { 11, 21, 76 },
new int[] { 5, 10, 37, 80 },
new int[] { 30, 49, 50, 94 },
new int[] { 13, 25, 48 });
System.out.println(Arrays.toString(merged));
Output
[5, 10, 11, 13, 21, 23, 25, 30, 37, 39, 48, 49, 50, 63, 68, 76, 80, 94]
Looks like a preparation exercise to motivate the introduction of array of arrays :)
Number the indices analogous to the lists to avoid confusion.
Identify the list with the smallest element at its current index. Avoid reading beyond the end of the array, as it will result in an exception.
Take this element and proceed.
int i1=0;
int i2=0;
int i3=0;
int n = a1.length + a2.length + a3.length;
for( int k = 0; k < n; k++) {
int advance = 0;
int value = Integer.MAX_VALUE;
if (i1 < a1.length && a1[i1] <= value) {
advance = 1;
value = a1[i1];
}
if (i2 < a2.length && a2[i2] <= value) {
advance = 2;
value = a2[i2];
}
if (i3 < a3.length && a3[i3] <= value) {
advance = 3;
value = a3[i3];
}
a[k] = value;
switch(advance) {
case 1: i1++; break;
case 2: i2++; break;
case 3: i3++; break;
}
}
A more efficient algorithm is to use a min-heap.
The algorithm is roughly described as follows:
First, construct a min-heap of size k (in this case size 3 for the three lists) taking the minimum elements in each list. You would then delete then the minimum element from the heap (noting which list it came from), add it to your newly constructed list, and then insert the next element from that same list which it was initially drawn from.
The time complexity would drop from O(n * k) to O(n * log(k)). Where n is the total number of elements in the final sorted list.
https://cs.stackexchange.com/questions/12853/heap-give-an-on-lg-k-time-algorithm-to-merge-k-sorted-lists-into-one-so
I have searched a lot in google but I didnt get any kind of solution I could use. Suppose input of array is:
{3,1,2,4,9,8,7,6,5,10}
then output must be like this:
{1,2,3,4,5,10,9,8,7,6}
by using Basic Java .
Your array: {3,1,2,4,9,8,7,6,5,10}
Sort it in ascending order: {1,2,3,4,5,6,7,8,9,10}
Break this array into two half arrays: {1,2,3,4,5}{6,7,8,9,10}
Sort the second array in descending order or reverse it: {10, 9,8,7,6}
Add the second array to the first array & you get: {1,2,3,4,5,10,9,8,7,6}
This would be the minimal code which uses an array of primitive ints:
static final int[] xs = {3,1,2,4,9,8,7,6,5,10};
static void sortAndReverse() {
Arrays.sort(xs);
for (int i = xs.length/2; i < dest(i); i++) {
int tmp = xs[i]; xs[i] = xs[dest(i)]; xs[dest(i)] = tmp;
}
System.out.println(Arrays.toString(xs));
}
static int dest(int i) { return 3*xs.length/2-i-1; }
If you're not ashamed of using wrapper objects, then this is unbeatable:
final Integer[] xs = {3,1,2,4,9,8,7,6,5,10};
final List<Integer> list = Arrays.asList(xs);
Collections.sort(list);
Collections.reverse(list.subList(list.size()/2, list.size()));
System.out.println(Arrays.toString(xs));
Please find the below code
import java.util.Arrays;
public class fre {
public static void main(String[] args) {
int[] vals = { 3, 1, 2, 4, 9, 8, 7, 6, 5, 10 };
Arrays.sort(vals); // Sorts the basic first array
int[] vals2 = Arrays.copyOfRange(vals, vals.length / 2, vals.length); // Gets the las values of the arrays i.e. it devies the array in multiple same part and another array is created
// Below loop will reverse the second array
for (int i = 0; i < vals2.length / 2; i++) {
int temp = vals2[i];
vals2[i] = vals2[vals2.length - 1 - i];
vals2[vals2.length - 1 - i] = temp;
}
vals = Arrays.copyOfRange(vals, 0, vals.length / 2);
// Final array array1and2 will be created where we will append first array with second array
int[] array1and2 = new int[vals.length + vals2.length];
System.arraycopy(vals, 0, array1and2, 0, vals.length);
System.arraycopy(vals2, 0, array1and2, vals.length, vals2.length);
// Prints the final result array
System.out.println(Arrays.toString(array1and2));
}
}
Output
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
You can use the java features to do this too ... Use
public static <T> void sort(T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
But the elements need to be objects ... The comparator needs to be changed while sorting the first half and second half of the array.
Should be a bit simpler than manually reversing each item in the second half.
Integer [] array = { 3,1,2,4,9,8,7,6,5,10 };
Arrays.sort(array);
Arrays.sort(array, array.length/2, array.length, new Comparator<Integer>(){
#Override
public int compare(Integer o1, Integer o2)
{
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
IPSOS isn't it?
int m;
if(array.length%2==0)
m=array.length/2;
else
m=(array.length+1)/2;
for(int i=0; i<array.length; ++i){
if(i<m){
int min = i;
for(int j=i+1; j<m;++j){
if(array[min]>array[j]){
min=j;
}
int tem = array[i];
array[i]=array[min];
array[min]=tem;
}
}
else {
int max = i;
for(int k=i+1; k<array.length; ++k){
if(array[max]<array[k]){
max=k;
}
int te = array[i];
array[i]=array[max];
array[max]=te;
}
}
}
for(int i=0;i<array.length;++i){
System.out.print(array[i] + " ");
}
1. Sort the array input_Array[]
2. j = lenght(input_Array)-1
3. loop i = lenght(input_Array)/2 to j
swap(input_Array[i] , input_Array[j-i])
input: 3,1,2,4,9,8,7,6,5,10
output: 1 3 5 7 9 10 8 6 4 2 (uniform acceding and descending )
public class AscendingDecending {
public static void main(String[]args) {
int a[]= {2,3,2,5,7,5,6,3};
int i,j,temp;
//Traverse the element of array
System.out.println("Input:");
for(i=0; i<a.length; i++) {
System.out.print(" "+ a[i]);
}
//lets move for ascending function
System.out.println("");
System.out.println("Output:");
//Create a Swap Function for sorting
for(i=0; i<a.length; i++) {
for(j=i+1; j<a.length; j++) {
if(a[i]>a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
//For Descending
for(i=0; i<a.length; i++) {
for(int j=i+1; j<a.length; j++) {
if(a[i]<a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
System.out.println(" ");
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
}
}
I hope this piece of code will help:
static void printarray(int[] arr, int len)
{
Arrays.sort(arr);
for (int i = 0; i < len / 2; i++)
System.out.println(arr[i]);
for (int j = len - 1; j >= len / 2; j--)
System.out.println(arr[j]);
}
This is what I need to do
Ability to reverse the contents of a single dimensional array of variable size, without using another temporary array.
Given a single dimensional array of integers, numbers, write the Java code to reverse the contents of numbers in-place without using a temporary array to store the reversed contents.
For example, if numbers is {12, 34, 50, 67, 88}, provide code that will alter numbers so that its contents now become {88, 67, 50, 34, 12}.
This is what I have
it is not working correctly.
public static int[] reverseArrayWithoutTempArray(int[] array) {
double array [ ];
array = new double [10];
int [ ] num = {12, 34, 50, 67, 88};
int i = 0;
int j = a.length - 1;
for (i = 0; i < a.length / 2; i++, j—){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return array;
}
It actually is working correctly for the example you provided. This is how my code looks like:
public static int[] reverseArrayWithoutTempArray(int[] a) {
int i = 0;
int j = a.length - 1;
for (i = 0; i < a.length / 2; i++, j--){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
That's it:
public static void reverseArrayWithoutTempArray(int[] num) {
int j = num.length - 1;
for (int i = 0; i < num.length / 2; i++, j --){
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
Calling of this method will be like:
int [] num = {12, 34, 50, 67, 88};
reverseArrayWithoutTempArray(num);
System.out.println(Arrays.toString(num)); //to log
You're basic algorithm is correct, but you code is a complete mess.
array is declared twice, once as a method parameter and once as a local variable. Get rid of the local reference.
The array num is ignored and isn't needed any way, get rid of it.
I don't know if it's a typo or not, but j— should be j--
does this work? (swap method is not implemented, but you know how to do it ,right?)
public static void reverseIntArray(int[] input) {
final int last = input.length - 1;
if (last < 0) {
return;
}
for (int i = 0; i < input.length / 2 + 1; i++) {
if (last - i <= i) {
return;
}
swap(input, i, last - i);
}
}
If this isn't coursework, you can use ArrayUtils.reverse.
Assuming you know how to implement swap the following reverses a part of array in-place:
public void reverse(int[] a, int low, int hi) {
while (low < hi) {
swap(low++, hi--, a);
}
}
You can then reverse the entire array by calling reverse(a, 0, a.length - 1).