Selection and Insertion sorts from scratch in Java
I am trying to find a good, basic way to make selection and insertion sorts so that I can manipulate them for other sorting techniques. How do these look? Is there a simpler way to write them?
package javaapplication59;
public class JavaApplication59 {
public static void main(String args) {
selectionSort ss = new selectionSort();
insertionSort is = new insertionSort();
int arr = {2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345};
arr = is.sort(arr);
System.out.print("{");
for (int el : arr) {
System.out.print(el + ",");
}
System.out.println("b}");
}
}
class insertionSort {
public int sort(int a) {
int insrt, j;
boolean keepGoing;
for (int i = 1; i < a.length; i++) {
insrt = a[i];
j = i - 1;
keepGoing = true;
while ((j >= 0) && keepGoing) {
if(insrt<a[j]){
a[j+1] = a[j];
j--;
if(j==-1)
a[0] = insrt;
}
else{
keepGoing = false;
a[j+1] = insrt;
}
}
}
return a;
}
}
class selectionSort {
public int sort(int arr) {
int min, minIndex;
for (int i = 0; i < arr.length; i++) {
min = arr[i];
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < min) {
min = arr[j];
minIndex = j;
}
}
arr[minIndex] = arr[i];
arr[i] = min;
}
return arr;
}
}
java algorithm sorting insertion-sort
add a comment |
I am trying to find a good, basic way to make selection and insertion sorts so that I can manipulate them for other sorting techniques. How do these look? Is there a simpler way to write them?
package javaapplication59;
public class JavaApplication59 {
public static void main(String args) {
selectionSort ss = new selectionSort();
insertionSort is = new insertionSort();
int arr = {2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345};
arr = is.sort(arr);
System.out.print("{");
for (int el : arr) {
System.out.print(el + ",");
}
System.out.println("b}");
}
}
class insertionSort {
public int sort(int a) {
int insrt, j;
boolean keepGoing;
for (int i = 1; i < a.length; i++) {
insrt = a[i];
j = i - 1;
keepGoing = true;
while ((j >= 0) && keepGoing) {
if(insrt<a[j]){
a[j+1] = a[j];
j--;
if(j==-1)
a[0] = insrt;
}
else{
keepGoing = false;
a[j+1] = insrt;
}
}
}
return a;
}
}
class selectionSort {
public int sort(int arr) {
int min, minIndex;
for (int i = 0; i < arr.length; i++) {
min = arr[i];
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < min) {
min = arr[j];
minIndex = j;
}
}
arr[minIndex] = arr[i];
arr[i] = min;
}
return arr;
}
}
java algorithm sorting insertion-sort
3
Consider usingjava.util.Arrays.toString(int)
for printing your array. Ie:System.out.println(java.util.Arrays.toString(arr));
– AJNeufeld
Nov 11 '18 at 22:32
add a comment |
I am trying to find a good, basic way to make selection and insertion sorts so that I can manipulate them for other sorting techniques. How do these look? Is there a simpler way to write them?
package javaapplication59;
public class JavaApplication59 {
public static void main(String args) {
selectionSort ss = new selectionSort();
insertionSort is = new insertionSort();
int arr = {2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345};
arr = is.sort(arr);
System.out.print("{");
for (int el : arr) {
System.out.print(el + ",");
}
System.out.println("b}");
}
}
class insertionSort {
public int sort(int a) {
int insrt, j;
boolean keepGoing;
for (int i = 1; i < a.length; i++) {
insrt = a[i];
j = i - 1;
keepGoing = true;
while ((j >= 0) && keepGoing) {
if(insrt<a[j]){
a[j+1] = a[j];
j--;
if(j==-1)
a[0] = insrt;
}
else{
keepGoing = false;
a[j+1] = insrt;
}
}
}
return a;
}
}
class selectionSort {
public int sort(int arr) {
int min, minIndex;
for (int i = 0; i < arr.length; i++) {
min = arr[i];
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < min) {
min = arr[j];
minIndex = j;
}
}
arr[minIndex] = arr[i];
arr[i] = min;
}
return arr;
}
}
java algorithm sorting insertion-sort
I am trying to find a good, basic way to make selection and insertion sorts so that I can manipulate them for other sorting techniques. How do these look? Is there a simpler way to write them?
package javaapplication59;
public class JavaApplication59 {
public static void main(String args) {
selectionSort ss = new selectionSort();
insertionSort is = new insertionSort();
int arr = {2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345};
arr = is.sort(arr);
System.out.print("{");
for (int el : arr) {
System.out.print(el + ",");
}
System.out.println("b}");
}
}
class insertionSort {
public int sort(int a) {
int insrt, j;
boolean keepGoing;
for (int i = 1; i < a.length; i++) {
insrt = a[i];
j = i - 1;
keepGoing = true;
while ((j >= 0) && keepGoing) {
if(insrt<a[j]){
a[j+1] = a[j];
j--;
if(j==-1)
a[0] = insrt;
}
else{
keepGoing = false;
a[j+1] = insrt;
}
}
}
return a;
}
}
class selectionSort {
public int sort(int arr) {
int min, minIndex;
for (int i = 0; i < arr.length; i++) {
min = arr[i];
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < min) {
min = arr[j];
minIndex = j;
}
}
arr[minIndex] = arr[i];
arr[i] = min;
}
return arr;
}
}
java algorithm sorting insertion-sort
java algorithm sorting insertion-sort
edited Nov 13 '18 at 5:04
Jamal♦
30.3k11116226
30.3k11116226
asked Nov 11 '18 at 15:39
tom smith
161
161
3
Consider usingjava.util.Arrays.toString(int)
for printing your array. Ie:System.out.println(java.util.Arrays.toString(arr));
– AJNeufeld
Nov 11 '18 at 22:32
add a comment |
3
Consider usingjava.util.Arrays.toString(int)
for printing your array. Ie:System.out.println(java.util.Arrays.toString(arr));
– AJNeufeld
Nov 11 '18 at 22:32
3
3
Consider using
java.util.Arrays.toString(int)
for printing your array. Ie: System.out.println(java.util.Arrays.toString(arr));
– AJNeufeld
Nov 11 '18 at 22:32
Consider using
java.util.Arrays.toString(int)
for printing your array. Ie: System.out.println(java.util.Arrays.toString(arr));
– AJNeufeld
Nov 11 '18 at 22:32
add a comment |
1 Answer
1
active
oldest
votes
Please try to follow the code formatting conventions of the language that you're using. This makes your code much more readable for other programmers.
If you use a Java IDE like Eclipse, NetBeans or IntelliJ it can format the code for you. In Eclipse this is triggered by pressing Ctrl+Shift+F.
Your use of CamelCase for identifiers is correct but only methods should start with lower case, class names start with a capital letter.
Don't abbreviate english words unnecessarily. Writing insrt
instead of insert
gains you nothing and makes the code harder to read.
You're defining classes that have the same behavior, so it would be good to define a common interface so you can use them interchangeable.
interface Sort {
void sort(int a);
}
class InsertionSort implements Sort {
// ...
}
class SelectionSort implements Sort {
// ...
}
For your print statement you can use StringJoiner
. It's specially built for your use case and allows you to specify a delimiter, prefix and suffix.
public static void main(String args) {
Sort ss = new SelectionSort();
Sort is = new InsertionSort();
int arr = { 2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345 };
is.sort(arr);
StringJoiner sj = new StringJoiner(",", "{", "}");
for (int el : arr) {
sj.add(String.valueOf(el));
}
System.out.println(sj);
}
Since you sort the array in-place (you don't create a new array during sort) for both algorithms you don't have to return the array. The reference that you hold on it outside is enough.
Your Insertion Sort can be simplified by getting rid of the keepGoing
boolean.
You move the conditional from the if statement into the head of the while loop.
You want the while loop to continue while a[j] > insrt
, no need for an extra variable. Then you move the actual insertion out of the else clause and put it after the while loop.
Your're going to be at the right insertion spot once the while loop has finished.
class InsertionSort implements Sort {
public void sort(int a) {
int insert, j;
for (int i = 1; i < a.length; i++) {
insert = a[i];
j = i - 1;
while ((j >= 0) && a[j] > insert) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = insert;
}
}
}
You SelectionSort looks fine to me.
Okay, thank you! I use NetBeans, and it was formatted using their format shortcut, but when I copied and pasted to Stack Overflow it messed it up. About the naming convention, thank you, and I will definitely follow that in future code.
– tom smith
Nov 11 '18 at 19:09
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
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: "196"
};
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: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
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%2fcodereview.stackexchange.com%2fquestions%2f207433%2fselection-and-insertion-sorts-from-scratch-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Please try to follow the code formatting conventions of the language that you're using. This makes your code much more readable for other programmers.
If you use a Java IDE like Eclipse, NetBeans or IntelliJ it can format the code for you. In Eclipse this is triggered by pressing Ctrl+Shift+F.
Your use of CamelCase for identifiers is correct but only methods should start with lower case, class names start with a capital letter.
Don't abbreviate english words unnecessarily. Writing insrt
instead of insert
gains you nothing and makes the code harder to read.
You're defining classes that have the same behavior, so it would be good to define a common interface so you can use them interchangeable.
interface Sort {
void sort(int a);
}
class InsertionSort implements Sort {
// ...
}
class SelectionSort implements Sort {
// ...
}
For your print statement you can use StringJoiner
. It's specially built for your use case and allows you to specify a delimiter, prefix and suffix.
public static void main(String args) {
Sort ss = new SelectionSort();
Sort is = new InsertionSort();
int arr = { 2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345 };
is.sort(arr);
StringJoiner sj = new StringJoiner(",", "{", "}");
for (int el : arr) {
sj.add(String.valueOf(el));
}
System.out.println(sj);
}
Since you sort the array in-place (you don't create a new array during sort) for both algorithms you don't have to return the array. The reference that you hold on it outside is enough.
Your Insertion Sort can be simplified by getting rid of the keepGoing
boolean.
You move the conditional from the if statement into the head of the while loop.
You want the while loop to continue while a[j] > insrt
, no need for an extra variable. Then you move the actual insertion out of the else clause and put it after the while loop.
Your're going to be at the right insertion spot once the while loop has finished.
class InsertionSort implements Sort {
public void sort(int a) {
int insert, j;
for (int i = 1; i < a.length; i++) {
insert = a[i];
j = i - 1;
while ((j >= 0) && a[j] > insert) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = insert;
}
}
}
You SelectionSort looks fine to me.
Okay, thank you! I use NetBeans, and it was formatted using their format shortcut, but when I copied and pasted to Stack Overflow it messed it up. About the naming convention, thank you, and I will definitely follow that in future code.
– tom smith
Nov 11 '18 at 19:09
add a comment |
Please try to follow the code formatting conventions of the language that you're using. This makes your code much more readable for other programmers.
If you use a Java IDE like Eclipse, NetBeans or IntelliJ it can format the code for you. In Eclipse this is triggered by pressing Ctrl+Shift+F.
Your use of CamelCase for identifiers is correct but only methods should start with lower case, class names start with a capital letter.
Don't abbreviate english words unnecessarily. Writing insrt
instead of insert
gains you nothing and makes the code harder to read.
You're defining classes that have the same behavior, so it would be good to define a common interface so you can use them interchangeable.
interface Sort {
void sort(int a);
}
class InsertionSort implements Sort {
// ...
}
class SelectionSort implements Sort {
// ...
}
For your print statement you can use StringJoiner
. It's specially built for your use case and allows you to specify a delimiter, prefix and suffix.
public static void main(String args) {
Sort ss = new SelectionSort();
Sort is = new InsertionSort();
int arr = { 2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345 };
is.sort(arr);
StringJoiner sj = new StringJoiner(",", "{", "}");
for (int el : arr) {
sj.add(String.valueOf(el));
}
System.out.println(sj);
}
Since you sort the array in-place (you don't create a new array during sort) for both algorithms you don't have to return the array. The reference that you hold on it outside is enough.
Your Insertion Sort can be simplified by getting rid of the keepGoing
boolean.
You move the conditional from the if statement into the head of the while loop.
You want the while loop to continue while a[j] > insrt
, no need for an extra variable. Then you move the actual insertion out of the else clause and put it after the while loop.
Your're going to be at the right insertion spot once the while loop has finished.
class InsertionSort implements Sort {
public void sort(int a) {
int insert, j;
for (int i = 1; i < a.length; i++) {
insert = a[i];
j = i - 1;
while ((j >= 0) && a[j] > insert) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = insert;
}
}
}
You SelectionSort looks fine to me.
Okay, thank you! I use NetBeans, and it was formatted using their format shortcut, but when I copied and pasted to Stack Overflow it messed it up. About the naming convention, thank you, and I will definitely follow that in future code.
– tom smith
Nov 11 '18 at 19:09
add a comment |
Please try to follow the code formatting conventions of the language that you're using. This makes your code much more readable for other programmers.
If you use a Java IDE like Eclipse, NetBeans or IntelliJ it can format the code for you. In Eclipse this is triggered by pressing Ctrl+Shift+F.
Your use of CamelCase for identifiers is correct but only methods should start with lower case, class names start with a capital letter.
Don't abbreviate english words unnecessarily. Writing insrt
instead of insert
gains you nothing and makes the code harder to read.
You're defining classes that have the same behavior, so it would be good to define a common interface so you can use them interchangeable.
interface Sort {
void sort(int a);
}
class InsertionSort implements Sort {
// ...
}
class SelectionSort implements Sort {
// ...
}
For your print statement you can use StringJoiner
. It's specially built for your use case and allows you to specify a delimiter, prefix and suffix.
public static void main(String args) {
Sort ss = new SelectionSort();
Sort is = new InsertionSort();
int arr = { 2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345 };
is.sort(arr);
StringJoiner sj = new StringJoiner(",", "{", "}");
for (int el : arr) {
sj.add(String.valueOf(el));
}
System.out.println(sj);
}
Since you sort the array in-place (you don't create a new array during sort) for both algorithms you don't have to return the array. The reference that you hold on it outside is enough.
Your Insertion Sort can be simplified by getting rid of the keepGoing
boolean.
You move the conditional from the if statement into the head of the while loop.
You want the while loop to continue while a[j] > insrt
, no need for an extra variable. Then you move the actual insertion out of the else clause and put it after the while loop.
Your're going to be at the right insertion spot once the while loop has finished.
class InsertionSort implements Sort {
public void sort(int a) {
int insert, j;
for (int i = 1; i < a.length; i++) {
insert = a[i];
j = i - 1;
while ((j >= 0) && a[j] > insert) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = insert;
}
}
}
You SelectionSort looks fine to me.
Please try to follow the code formatting conventions of the language that you're using. This makes your code much more readable for other programmers.
If you use a Java IDE like Eclipse, NetBeans or IntelliJ it can format the code for you. In Eclipse this is triggered by pressing Ctrl+Shift+F.
Your use of CamelCase for identifiers is correct but only methods should start with lower case, class names start with a capital letter.
Don't abbreviate english words unnecessarily. Writing insrt
instead of insert
gains you nothing and makes the code harder to read.
You're defining classes that have the same behavior, so it would be good to define a common interface so you can use them interchangeable.
interface Sort {
void sort(int a);
}
class InsertionSort implements Sort {
// ...
}
class SelectionSort implements Sort {
// ...
}
For your print statement you can use StringJoiner
. It's specially built for your use case and allows you to specify a delimiter, prefix and suffix.
public static void main(String args) {
Sort ss = new SelectionSort();
Sort is = new InsertionSort();
int arr = { 2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345 };
is.sort(arr);
StringJoiner sj = new StringJoiner(",", "{", "}");
for (int el : arr) {
sj.add(String.valueOf(el));
}
System.out.println(sj);
}
Since you sort the array in-place (you don't create a new array during sort) for both algorithms you don't have to return the array. The reference that you hold on it outside is enough.
Your Insertion Sort can be simplified by getting rid of the keepGoing
boolean.
You move the conditional from the if statement into the head of the while loop.
You want the while loop to continue while a[j] > insrt
, no need for an extra variable. Then you move the actual insertion out of the else clause and put it after the while loop.
Your're going to be at the right insertion spot once the while loop has finished.
class InsertionSort implements Sort {
public void sort(int a) {
int insert, j;
for (int i = 1; i < a.length; i++) {
insert = a[i];
j = i - 1;
while ((j >= 0) && a[j] > insert) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = insert;
}
}
}
You SelectionSort looks fine to me.
answered Nov 11 '18 at 18:47
fap
1615
1615
Okay, thank you! I use NetBeans, and it was formatted using their format shortcut, but when I copied and pasted to Stack Overflow it messed it up. About the naming convention, thank you, and I will definitely follow that in future code.
– tom smith
Nov 11 '18 at 19:09
add a comment |
Okay, thank you! I use NetBeans, and it was formatted using their format shortcut, but when I copied and pasted to Stack Overflow it messed it up. About the naming convention, thank you, and I will definitely follow that in future code.
– tom smith
Nov 11 '18 at 19:09
Okay, thank you! I use NetBeans, and it was formatted using their format shortcut, but when I copied and pasted to Stack Overflow it messed it up. About the naming convention, thank you, and I will definitely follow that in future code.
– tom smith
Nov 11 '18 at 19:09
Okay, thank you! I use NetBeans, and it was formatted using their format shortcut, but when I copied and pasted to Stack Overflow it messed it up. About the naming convention, thank you, and I will definitely follow that in future code.
– tom smith
Nov 11 '18 at 19:09
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- 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.
Use MathJax to format equations. MathJax reference.
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%2fcodereview.stackexchange.com%2fquestions%2f207433%2fselection-and-insertion-sorts-from-scratch-in-java%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
3
Consider using
java.util.Arrays.toString(int)
for printing your array. Ie:System.out.println(java.util.Arrays.toString(arr));
– AJNeufeld
Nov 11 '18 at 22:32