Java sorting array positive ascending to negative ascending
I can't solve the problem , where I need output from array A like 1,2,3,4,-1,-2,-3,-4
from random numbers in array, then write it to another array B. So far my experimental code doesn't work as I'd
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
Output is 5 4 3 2 1 -2 -3 -30 , but I need 1,2,3,4,5,-2,-3,-30
Update:
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30,-1,-15,8;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
I got closer to my target but 8 1 2 3 4 5 -1 -2 -3 -15 -30 , that number 8 ruins it all
java arrays
add a comment |
I can't solve the problem , where I need output from array A like 1,2,3,4,-1,-2,-3,-4
from random numbers in array, then write it to another array B. So far my experimental code doesn't work as I'd
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
Output is 5 4 3 2 1 -2 -3 -30 , but I need 1,2,3,4,5,-2,-3,-30
Update:
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30,-1,-15,8;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
I got closer to my target but 8 1 2 3 4 5 -1 -2 -3 -15 -30 , that number 8 ruins it all
java arrays
1
you might want to split the input into two lists of negative and positive integers, then sort them and then merge accordingly.
– nullpointer
Nov 10 at 16:59
You'll probably just want to write a custom comparator (stackoverflow.com/questions/5245093/…) that sorts first by sign, and then in ascending order by absolute value.
– CollinD
Nov 10 at 17:05
I am not experienced enough to use comparator...
– Mezja
Nov 10 at 17:28
add a comment |
I can't solve the problem , where I need output from array A like 1,2,3,4,-1,-2,-3,-4
from random numbers in array, then write it to another array B. So far my experimental code doesn't work as I'd
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
Output is 5 4 3 2 1 -2 -3 -30 , but I need 1,2,3,4,5,-2,-3,-30
Update:
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30,-1,-15,8;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
I got closer to my target but 8 1 2 3 4 5 -1 -2 -3 -15 -30 , that number 8 ruins it all
java arrays
I can't solve the problem , where I need output from array A like 1,2,3,4,-1,-2,-3,-4
from random numbers in array, then write it to another array B. So far my experimental code doesn't work as I'd
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
Output is 5 4 3 2 1 -2 -3 -30 , but I need 1,2,3,4,5,-2,-3,-30
Update:
public static void main(String args)
int a = 5,4,3,2,1,-3,-2,-30,-1,-15,8;
int length = a.length - 1;
for (int i = 0 ; i < length ; i++)
for (int j = 0 ; j < length-i ; j++)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
for (int x : a)
System.out.print(x+" ");
I got closer to my target but 8 1 2 3 4 5 -1 -2 -3 -15 -30 , that number 8 ruins it all
java arrays
java arrays
edited Nov 11 at 10:12
quant
1,59211526
1,59211526
asked Nov 10 at 16:56
Mezja
83
83
1
you might want to split the input into two lists of negative and positive integers, then sort them and then merge accordingly.
– nullpointer
Nov 10 at 16:59
You'll probably just want to write a custom comparator (stackoverflow.com/questions/5245093/…) that sorts first by sign, and then in ascending order by absolute value.
– CollinD
Nov 10 at 17:05
I am not experienced enough to use comparator...
– Mezja
Nov 10 at 17:28
add a comment |
1
you might want to split the input into two lists of negative and positive integers, then sort them and then merge accordingly.
– nullpointer
Nov 10 at 16:59
You'll probably just want to write a custom comparator (stackoverflow.com/questions/5245093/…) that sorts first by sign, and then in ascending order by absolute value.
– CollinD
Nov 10 at 17:05
I am not experienced enough to use comparator...
– Mezja
Nov 10 at 17:28
1
1
you might want to split the input into two lists of negative and positive integers, then sort them and then merge accordingly.
– nullpointer
Nov 10 at 16:59
you might want to split the input into two lists of negative and positive integers, then sort them and then merge accordingly.
– nullpointer
Nov 10 at 16:59
You'll probably just want to write a custom comparator (stackoverflow.com/questions/5245093/…) that sorts first by sign, and then in ascending order by absolute value.
– CollinD
Nov 10 at 17:05
You'll probably just want to write a custom comparator (stackoverflow.com/questions/5245093/…) that sorts first by sign, and then in ascending order by absolute value.
– CollinD
Nov 10 at 17:05
I am not experienced enough to use comparator...
– Mezja
Nov 10 at 17:28
I am not experienced enough to use comparator...
– Mezja
Nov 10 at 17:28
add a comment |
6 Answers
6
active
oldest
votes
Add an if-else to differentiate the positive and negative case.
if (a[j] < 0)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
I get output- 4 3 2 1 5 -2 -3 -30
– Mezja
Nov 10 at 17:27
Copy the code and insert it into the internal for. In your updated code you miss the if condition
– Cesare Fischetti
Nov 10 at 18:07
Thank you for your help, I managed to make my code work based on your code idea! :)
– Mezja
Nov 11 at 12:10
add a comment |
If I understand you correctly you want to sort after two things. Positive numbers from low to high and negative numbers from high to low.
You could first sort from high to low and in a second run over the array skip all positives and then sort from high to low.
Does this help?
I could write some code, but I believe that's something you want to learn right now :)
Did it actually help?
– user10419911
Nov 11 at 16:29
Yes,it did help! :)
– Mezja
Nov 13 at 13:41
Then I am happy and thanks for the feedback :D
– user10419911
Nov 13 at 14:01
add a comment |
Algo:
Traverse the Array and Store positives in one and Negatives in another. O(i)
Sort the positives array in ascending order. O(mLog(m))
Sort the negatives indescending order. O(nLog(n))
Create a final array of the size of the input.
Add all the positive array sorted values. Then add the negative array sorted values. O(i)
Total : O(i) + O(mLog(m)) + O(nLog(n)) + O(i) = O(mLog(m)) if m > n
Thank you for your tip! :)
– Mezja
Nov 11 at 12:12
add a comment |
I have used library functions here. But if you want you can the write the functions using the same idea.
public class PostivieAsendingNegativeDesending implements Comparator<Integer>
public static void main(String args)
int fullList = 5, 4, 3, 2, 1, -3, -2, -30;
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++)
if (fullList[i] < 0)
subList2.add((fullList[i]));
else
subList.add(fullList[i]);
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++)
System.out.print(subList.get(i) + " ");
System.out.println("");
@Override
public int compare(Integer n1, Integer n2)
return n2 - n1;
add a comment |
This will do the trick which uses only basic loops
public static void main(String args)
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int length = a.length - 1;
int pos = 0, neg = 0;
// find total count of positive and negative numbers
for (int i = 0; i <= length; i++)
if (a[i] < 0)
neg++;
else
pos++;
// initialize the arrays based on 'pos' and 'neg'
int posArr = new int[pos];
int negArr = new int[neg];
// store pos and neg values in the arrays
int countPos = 0, countNeg = 0;
for (int i = 0; i <= length; i++)
if (a[i] < 0)
negArr[countNeg] = a[i];
countNeg++;
else
posArr[countPos] = a[i];
countPos++;
// sort positive numbers
for (int i = 0; i < posArr.length - 1; i++)
for (int j = 0; j < posArr.length - 1 - i; j++)
if (posArr[j] > posArr[j + 1])
int swap = posArr[j];
posArr[j] = posArr[j + 1];
posArr[j + 1] = swap;
// sort negative numbers
for (int i = 0; i < negArr.length - 1; i++)
for (int j = 0; j < negArr.length - 1 - i; j++)
if (negArr[j] < negArr[j + 1])
int swap = negArr[j];
negArr[j] = negArr[j + 1];
negArr[j + 1] = swap;
// 1. print out posArr and then negArr
// or
// 2. merge them into another array and print
Logic is explained below :
Find total count of positive and negative numbers.
Create and store the positive and negative values in the respective arrays.
Sort positive array in ascending order.
Sort negative array in descending order.
Print out positive array followed by the negative array OR merge them into another and print.
add a comment |
I suggest another approach. You should try to formulate the rules to which the exact comparison must adhere.
Your requirement seem to have the following rules:
- Positive numbers always come before negative numbers.
- Positive numbers are ordered in ascending order.
- Negative numbers are ordered in descending order. Yes, I said descending. Since higher numbers come before lower numbers, i.e. −2 is greater than −7.
Warning: you are using a nested for loop, which means that the process time will grow exponentially if the array becomes larger. The good news is: you don't need to nest a for loop into another for loop. I suggest writing a Comparator
instead:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0)
return -1;
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0)
return 1;
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else
return (i < 0 ? j - i : i - j);
Your code could look like this:
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> ... )
.mapToInt(i -> i)
.toArray();
Lambda expressions are a new concept from Java 8. The Java Tutorials provide some valuable information.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241244%2fjava-sorting-array-positive-ascending-to-negative-ascending%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Add an if-else to differentiate the positive and negative case.
if (a[j] < 0)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
I get output- 4 3 2 1 5 -2 -3 -30
– Mezja
Nov 10 at 17:27
Copy the code and insert it into the internal for. In your updated code you miss the if condition
– Cesare Fischetti
Nov 10 at 18:07
Thank you for your help, I managed to make my code work based on your code idea! :)
– Mezja
Nov 11 at 12:10
add a comment |
Add an if-else to differentiate the positive and negative case.
if (a[j] < 0)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
I get output- 4 3 2 1 5 -2 -3 -30
– Mezja
Nov 10 at 17:27
Copy the code and insert it into the internal for. In your updated code you miss the if condition
– Cesare Fischetti
Nov 10 at 18:07
Thank you for your help, I managed to make my code work based on your code idea! :)
– Mezja
Nov 11 at 12:10
add a comment |
Add an if-else to differentiate the positive and negative case.
if (a[j] < 0)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
Add an if-else to differentiate the positive and negative case.
if (a[j] < 0)
if (a[j] < a[j+1])
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
else
if (a[j] > a[j+1] && a[j+1] > 0)
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
edited Nov 11 at 8:10
quant
1,59211526
1,59211526
answered Nov 10 at 17:13
Cesare Fischetti
1015
1015
I get output- 4 3 2 1 5 -2 -3 -30
– Mezja
Nov 10 at 17:27
Copy the code and insert it into the internal for. In your updated code you miss the if condition
– Cesare Fischetti
Nov 10 at 18:07
Thank you for your help, I managed to make my code work based on your code idea! :)
– Mezja
Nov 11 at 12:10
add a comment |
I get output- 4 3 2 1 5 -2 -3 -30
– Mezja
Nov 10 at 17:27
Copy the code and insert it into the internal for. In your updated code you miss the if condition
– Cesare Fischetti
Nov 10 at 18:07
Thank you for your help, I managed to make my code work based on your code idea! :)
– Mezja
Nov 11 at 12:10
I get output- 4 3 2 1 5 -2 -3 -30
– Mezja
Nov 10 at 17:27
I get output- 4 3 2 1 5 -2 -3 -30
– Mezja
Nov 10 at 17:27
Copy the code and insert it into the internal for. In your updated code you miss the if condition
– Cesare Fischetti
Nov 10 at 18:07
Copy the code and insert it into the internal for. In your updated code you miss the if condition
– Cesare Fischetti
Nov 10 at 18:07
Thank you for your help, I managed to make my code work based on your code idea! :)
– Mezja
Nov 11 at 12:10
Thank you for your help, I managed to make my code work based on your code idea! :)
– Mezja
Nov 11 at 12:10
add a comment |
If I understand you correctly you want to sort after two things. Positive numbers from low to high and negative numbers from high to low.
You could first sort from high to low and in a second run over the array skip all positives and then sort from high to low.
Does this help?
I could write some code, but I believe that's something you want to learn right now :)
Did it actually help?
– user10419911
Nov 11 at 16:29
Yes,it did help! :)
– Mezja
Nov 13 at 13:41
Then I am happy and thanks for the feedback :D
– user10419911
Nov 13 at 14:01
add a comment |
If I understand you correctly you want to sort after two things. Positive numbers from low to high and negative numbers from high to low.
You could first sort from high to low and in a second run over the array skip all positives and then sort from high to low.
Does this help?
I could write some code, but I believe that's something you want to learn right now :)
Did it actually help?
– user10419911
Nov 11 at 16:29
Yes,it did help! :)
– Mezja
Nov 13 at 13:41
Then I am happy and thanks for the feedback :D
– user10419911
Nov 13 at 14:01
add a comment |
If I understand you correctly you want to sort after two things. Positive numbers from low to high and negative numbers from high to low.
You could first sort from high to low and in a second run over the array skip all positives and then sort from high to low.
Does this help?
I could write some code, but I believe that's something you want to learn right now :)
If I understand you correctly you want to sort after two things. Positive numbers from low to high and negative numbers from high to low.
You could first sort from high to low and in a second run over the array skip all positives and then sort from high to low.
Does this help?
I could write some code, but I believe that's something you want to learn right now :)
answered Nov 10 at 17:03
user10419911
Did it actually help?
– user10419911
Nov 11 at 16:29
Yes,it did help! :)
– Mezja
Nov 13 at 13:41
Then I am happy and thanks for the feedback :D
– user10419911
Nov 13 at 14:01
add a comment |
Did it actually help?
– user10419911
Nov 11 at 16:29
Yes,it did help! :)
– Mezja
Nov 13 at 13:41
Then I am happy and thanks for the feedback :D
– user10419911
Nov 13 at 14:01
Did it actually help?
– user10419911
Nov 11 at 16:29
Did it actually help?
– user10419911
Nov 11 at 16:29
Yes,it did help! :)
– Mezja
Nov 13 at 13:41
Yes,it did help! :)
– Mezja
Nov 13 at 13:41
Then I am happy and thanks for the feedback :D
– user10419911
Nov 13 at 14:01
Then I am happy and thanks for the feedback :D
– user10419911
Nov 13 at 14:01
add a comment |
Algo:
Traverse the Array and Store positives in one and Negatives in another. O(i)
Sort the positives array in ascending order. O(mLog(m))
Sort the negatives indescending order. O(nLog(n))
Create a final array of the size of the input.
Add all the positive array sorted values. Then add the negative array sorted values. O(i)
Total : O(i) + O(mLog(m)) + O(nLog(n)) + O(i) = O(mLog(m)) if m > n
Thank you for your tip! :)
– Mezja
Nov 11 at 12:12
add a comment |
Algo:
Traverse the Array and Store positives in one and Negatives in another. O(i)
Sort the positives array in ascending order. O(mLog(m))
Sort the negatives indescending order. O(nLog(n))
Create a final array of the size of the input.
Add all the positive array sorted values. Then add the negative array sorted values. O(i)
Total : O(i) + O(mLog(m)) + O(nLog(n)) + O(i) = O(mLog(m)) if m > n
Thank you for your tip! :)
– Mezja
Nov 11 at 12:12
add a comment |
Algo:
Traverse the Array and Store positives in one and Negatives in another. O(i)
Sort the positives array in ascending order. O(mLog(m))
Sort the negatives indescending order. O(nLog(n))
Create a final array of the size of the input.
Add all the positive array sorted values. Then add the negative array sorted values. O(i)
Total : O(i) + O(mLog(m)) + O(nLog(n)) + O(i) = O(mLog(m)) if m > n
Algo:
Traverse the Array and Store positives in one and Negatives in another. O(i)
Sort the positives array in ascending order. O(mLog(m))
Sort the negatives indescending order. O(nLog(n))
Create a final array of the size of the input.
Add all the positive array sorted values. Then add the negative array sorted values. O(i)
Total : O(i) + O(mLog(m)) + O(nLog(n)) + O(i) = O(mLog(m)) if m > n
answered Nov 10 at 17:30
janardhan sharma
2537
2537
Thank you for your tip! :)
– Mezja
Nov 11 at 12:12
add a comment |
Thank you for your tip! :)
– Mezja
Nov 11 at 12:12
Thank you for your tip! :)
– Mezja
Nov 11 at 12:12
Thank you for your tip! :)
– Mezja
Nov 11 at 12:12
add a comment |
I have used library functions here. But if you want you can the write the functions using the same idea.
public class PostivieAsendingNegativeDesending implements Comparator<Integer>
public static void main(String args)
int fullList = 5, 4, 3, 2, 1, -3, -2, -30;
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++)
if (fullList[i] < 0)
subList2.add((fullList[i]));
else
subList.add(fullList[i]);
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++)
System.out.print(subList.get(i) + " ");
System.out.println("");
@Override
public int compare(Integer n1, Integer n2)
return n2 - n1;
add a comment |
I have used library functions here. But if you want you can the write the functions using the same idea.
public class PostivieAsendingNegativeDesending implements Comparator<Integer>
public static void main(String args)
int fullList = 5, 4, 3, 2, 1, -3, -2, -30;
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++)
if (fullList[i] < 0)
subList2.add((fullList[i]));
else
subList.add(fullList[i]);
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++)
System.out.print(subList.get(i) + " ");
System.out.println("");
@Override
public int compare(Integer n1, Integer n2)
return n2 - n1;
add a comment |
I have used library functions here. But if you want you can the write the functions using the same idea.
public class PostivieAsendingNegativeDesending implements Comparator<Integer>
public static void main(String args)
int fullList = 5, 4, 3, 2, 1, -3, -2, -30;
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++)
if (fullList[i] < 0)
subList2.add((fullList[i]));
else
subList.add(fullList[i]);
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++)
System.out.print(subList.get(i) + " ");
System.out.println("");
@Override
public int compare(Integer n1, Integer n2)
return n2 - n1;
I have used library functions here. But if you want you can the write the functions using the same idea.
public class PostivieAsendingNegativeDesending implements Comparator<Integer>
public static void main(String args)
int fullList = 5, 4, 3, 2, 1, -3, -2, -30;
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++)
if (fullList[i] < 0)
subList2.add((fullList[i]));
else
subList.add(fullList[i]);
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++)
System.out.print(subList.get(i) + " ");
System.out.println("");
@Override
public int compare(Integer n1, Integer n2)
return n2 - n1;
answered Nov 10 at 17:40
Moshiur Rahman
15117
15117
add a comment |
add a comment |
This will do the trick which uses only basic loops
public static void main(String args)
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int length = a.length - 1;
int pos = 0, neg = 0;
// find total count of positive and negative numbers
for (int i = 0; i <= length; i++)
if (a[i] < 0)
neg++;
else
pos++;
// initialize the arrays based on 'pos' and 'neg'
int posArr = new int[pos];
int negArr = new int[neg];
// store pos and neg values in the arrays
int countPos = 0, countNeg = 0;
for (int i = 0; i <= length; i++)
if (a[i] < 0)
negArr[countNeg] = a[i];
countNeg++;
else
posArr[countPos] = a[i];
countPos++;
// sort positive numbers
for (int i = 0; i < posArr.length - 1; i++)
for (int j = 0; j < posArr.length - 1 - i; j++)
if (posArr[j] > posArr[j + 1])
int swap = posArr[j];
posArr[j] = posArr[j + 1];
posArr[j + 1] = swap;
// sort negative numbers
for (int i = 0; i < negArr.length - 1; i++)
for (int j = 0; j < negArr.length - 1 - i; j++)
if (negArr[j] < negArr[j + 1])
int swap = negArr[j];
negArr[j] = negArr[j + 1];
negArr[j + 1] = swap;
// 1. print out posArr and then negArr
// or
// 2. merge them into another array and print
Logic is explained below :
Find total count of positive and negative numbers.
Create and store the positive and negative values in the respective arrays.
Sort positive array in ascending order.
Sort negative array in descending order.
Print out positive array followed by the negative array OR merge them into another and print.
add a comment |
This will do the trick which uses only basic loops
public static void main(String args)
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int length = a.length - 1;
int pos = 0, neg = 0;
// find total count of positive and negative numbers
for (int i = 0; i <= length; i++)
if (a[i] < 0)
neg++;
else
pos++;
// initialize the arrays based on 'pos' and 'neg'
int posArr = new int[pos];
int negArr = new int[neg];
// store pos and neg values in the arrays
int countPos = 0, countNeg = 0;
for (int i = 0; i <= length; i++)
if (a[i] < 0)
negArr[countNeg] = a[i];
countNeg++;
else
posArr[countPos] = a[i];
countPos++;
// sort positive numbers
for (int i = 0; i < posArr.length - 1; i++)
for (int j = 0; j < posArr.length - 1 - i; j++)
if (posArr[j] > posArr[j + 1])
int swap = posArr[j];
posArr[j] = posArr[j + 1];
posArr[j + 1] = swap;
// sort negative numbers
for (int i = 0; i < negArr.length - 1; i++)
for (int j = 0; j < negArr.length - 1 - i; j++)
if (negArr[j] < negArr[j + 1])
int swap = negArr[j];
negArr[j] = negArr[j + 1];
negArr[j + 1] = swap;
// 1. print out posArr and then negArr
// or
// 2. merge them into another array and print
Logic is explained below :
Find total count of positive and negative numbers.
Create and store the positive and negative values in the respective arrays.
Sort positive array in ascending order.
Sort negative array in descending order.
Print out positive array followed by the negative array OR merge them into another and print.
add a comment |
This will do the trick which uses only basic loops
public static void main(String args)
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int length = a.length - 1;
int pos = 0, neg = 0;
// find total count of positive and negative numbers
for (int i = 0; i <= length; i++)
if (a[i] < 0)
neg++;
else
pos++;
// initialize the arrays based on 'pos' and 'neg'
int posArr = new int[pos];
int negArr = new int[neg];
// store pos and neg values in the arrays
int countPos = 0, countNeg = 0;
for (int i = 0; i <= length; i++)
if (a[i] < 0)
negArr[countNeg] = a[i];
countNeg++;
else
posArr[countPos] = a[i];
countPos++;
// sort positive numbers
for (int i = 0; i < posArr.length - 1; i++)
for (int j = 0; j < posArr.length - 1 - i; j++)
if (posArr[j] > posArr[j + 1])
int swap = posArr[j];
posArr[j] = posArr[j + 1];
posArr[j + 1] = swap;
// sort negative numbers
for (int i = 0; i < negArr.length - 1; i++)
for (int j = 0; j < negArr.length - 1 - i; j++)
if (negArr[j] < negArr[j + 1])
int swap = negArr[j];
negArr[j] = negArr[j + 1];
negArr[j + 1] = swap;
// 1. print out posArr and then negArr
// or
// 2. merge them into another array and print
Logic is explained below :
Find total count of positive and negative numbers.
Create and store the positive and negative values in the respective arrays.
Sort positive array in ascending order.
Sort negative array in descending order.
Print out positive array followed by the negative array OR merge them into another and print.
This will do the trick which uses only basic loops
public static void main(String args)
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int length = a.length - 1;
int pos = 0, neg = 0;
// find total count of positive and negative numbers
for (int i = 0; i <= length; i++)
if (a[i] < 0)
neg++;
else
pos++;
// initialize the arrays based on 'pos' and 'neg'
int posArr = new int[pos];
int negArr = new int[neg];
// store pos and neg values in the arrays
int countPos = 0, countNeg = 0;
for (int i = 0; i <= length; i++)
if (a[i] < 0)
negArr[countNeg] = a[i];
countNeg++;
else
posArr[countPos] = a[i];
countPos++;
// sort positive numbers
for (int i = 0; i < posArr.length - 1; i++)
for (int j = 0; j < posArr.length - 1 - i; j++)
if (posArr[j] > posArr[j + 1])
int swap = posArr[j];
posArr[j] = posArr[j + 1];
posArr[j + 1] = swap;
// sort negative numbers
for (int i = 0; i < negArr.length - 1; i++)
for (int j = 0; j < negArr.length - 1 - i; j++)
if (negArr[j] < negArr[j + 1])
int swap = negArr[j];
negArr[j] = negArr[j + 1];
negArr[j + 1] = swap;
// 1. print out posArr and then negArr
// or
// 2. merge them into another array and print
Logic is explained below :
Find total count of positive and negative numbers.
Create and store the positive and negative values in the respective arrays.
Sort positive array in ascending order.
Sort negative array in descending order.
Print out positive array followed by the negative array OR merge them into another and print.
edited Nov 10 at 18:30
answered Nov 10 at 17:58
Nicholas K
5,07751031
5,07751031
add a comment |
add a comment |
I suggest another approach. You should try to formulate the rules to which the exact comparison must adhere.
Your requirement seem to have the following rules:
- Positive numbers always come before negative numbers.
- Positive numbers are ordered in ascending order.
- Negative numbers are ordered in descending order. Yes, I said descending. Since higher numbers come before lower numbers, i.e. −2 is greater than −7.
Warning: you are using a nested for loop, which means that the process time will grow exponentially if the array becomes larger. The good news is: you don't need to nest a for loop into another for loop. I suggest writing a Comparator
instead:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0)
return -1;
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0)
return 1;
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else
return (i < 0 ? j - i : i - j);
Your code could look like this:
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> ... )
.mapToInt(i -> i)
.toArray();
Lambda expressions are a new concept from Java 8. The Java Tutorials provide some valuable information.
add a comment |
I suggest another approach. You should try to formulate the rules to which the exact comparison must adhere.
Your requirement seem to have the following rules:
- Positive numbers always come before negative numbers.
- Positive numbers are ordered in ascending order.
- Negative numbers are ordered in descending order. Yes, I said descending. Since higher numbers come before lower numbers, i.e. −2 is greater than −7.
Warning: you are using a nested for loop, which means that the process time will grow exponentially if the array becomes larger. The good news is: you don't need to nest a for loop into another for loop. I suggest writing a Comparator
instead:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0)
return -1;
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0)
return 1;
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else
return (i < 0 ? j - i : i - j);
Your code could look like this:
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> ... )
.mapToInt(i -> i)
.toArray();
Lambda expressions are a new concept from Java 8. The Java Tutorials provide some valuable information.
add a comment |
I suggest another approach. You should try to formulate the rules to which the exact comparison must adhere.
Your requirement seem to have the following rules:
- Positive numbers always come before negative numbers.
- Positive numbers are ordered in ascending order.
- Negative numbers are ordered in descending order. Yes, I said descending. Since higher numbers come before lower numbers, i.e. −2 is greater than −7.
Warning: you are using a nested for loop, which means that the process time will grow exponentially if the array becomes larger. The good news is: you don't need to nest a for loop into another for loop. I suggest writing a Comparator
instead:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0)
return -1;
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0)
return 1;
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else
return (i < 0 ? j - i : i - j);
Your code could look like this:
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> ... )
.mapToInt(i -> i)
.toArray();
Lambda expressions are a new concept from Java 8. The Java Tutorials provide some valuable information.
I suggest another approach. You should try to formulate the rules to which the exact comparison must adhere.
Your requirement seem to have the following rules:
- Positive numbers always come before negative numbers.
- Positive numbers are ordered in ascending order.
- Negative numbers are ordered in descending order. Yes, I said descending. Since higher numbers come before lower numbers, i.e. −2 is greater than −7.
Warning: you are using a nested for loop, which means that the process time will grow exponentially if the array becomes larger. The good news is: you don't need to nest a for loop into another for loop. I suggest writing a Comparator
instead:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0)
return -1;
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0)
return 1;
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else
return (i < 0 ? j - i : i - j);
Your code could look like this:
int a = 5, 4, 3, 2, 1, -3, -2, -30 ;
int yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> ... )
.mapToInt(i -> i)
.toArray();
Lambda expressions are a new concept from Java 8. The Java Tutorials provide some valuable information.
edited Nov 12 at 10:20
answered Nov 12 at 9:31
MC Emperor
8,018125387
8,018125387
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241244%2fjava-sorting-array-positive-ascending-to-negative-ascending%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
you might want to split the input into two lists of negative and positive integers, then sort them and then merge accordingly.
– nullpointer
Nov 10 at 16:59
You'll probably just want to write a custom comparator (stackoverflow.com/questions/5245093/…) that sorts first by sign, and then in ascending order by absolute value.
– CollinD
Nov 10 at 17:05
I am not experienced enough to use comparator...
– Mezja
Nov 10 at 17:28