Implementation of moving algorithms before and after positive and negative elements in an array (with 0 as the dividing line)

Source: Internet
Author: User

Package test;


/**
* Implement the moving algorithm before and after the positive and negative elements of the array (the division line is 0 and can be any other number)
* Move a negative number forward to the front of the array, and place a positive number behind it.
* @ Author hao
*
*/
Public class MoveNumTest {


/**
* @ Param args
*/
Public static void main (String [] args ){
Int [] nums = {342,6, 3453645,-324, 1, 6,-4,645,-3534, 34,-3,345,989 56,-6 };
MoveNumTest test = new MoveNumTest ();
Test. movenum1 (nums );
Test. movenum2 (nums );
}

Private void movenum2 (int [] nums ){
Int left = 0;
Int right = nums. length-1;
While (left <right ){
Int tmpLeft = 0;
For (; left <right; left ++ ){
If (nums [left]> 0 ){
TmpLeft = nums [left];
Break;
}
}
If (tmpLeft! = 0 ){
For (; right> left; right --){
If (nums [right] <0 ){
Nums [left] = nums [right];
Nums [right] = tmpLeft;
Break;
}
}
}
}


System. out. println ("\ nleft =" + left + ", right =" + right );
For (int I: nums ){
System. out. print (I + "");
}
}


Private void movenum1 (int [] nums ){
Int left = 0;
Int right = nums. length-1;
While (left <right ){
Int tmpLeft = 0;
For (; left <right; left ++ ){
If (nums [left]> 0 ){
TmpLeft = nums [left];
Break;
}
}
Int tmpRight = 0;
For (; right> left; right --){
If (nums [right] <0 ){
TmpRight = nums [right];
Break;
}
}
If (tmpLeft! = 0 & tmpRight! = 0 ){
Nums [left] = tmpRight;
Nums [right] = tmpLeft;
}
}


System. out. println ("left =" + left + ", right =" + right );
For (int I: nums ){
System. out. print (I + "");
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.