This week's book giveaway is in the HTML Pages with CSS and JavaScript forum.
We're giving away four copies of Testing JavaScript Applications and have Lucas da Costa on-line!
See this thread for details.
Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Sorting an array question?

 
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have included below two different ways in which I can sort an array; that I know right now.  Could someone please explain to me the benefit of either one over the other? I also realize there are probably lots of other ways to sort this so if you would like to  share them please do. I am more so trying to understand the logic behind the method of sorting and it took me a little while to wrap my head around these two options.


Method 1  to sort array


Method 2 to sort array using Arrays.copyOf()
 
Greenhorn
Posts: 24
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! There are many other ways to sort any kind of Array. A non constructive way but straight forward would be to use " Collections.sort(arrayname); ". To check if it works only with ArrayLists or it works with any other Array.
You could check this link for a full example of code: https://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/
 
Marshal
Posts: 69859
278
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both those methods have the advantage that you are copying the original array, rather than Arrays#sort() which has the array sent rather like an output parameter; you are changing the state of the array passed as an argument. I would prefer to use the clone() method to copy the array. I would also put such methods into a utility class. I wouldn't have lines 11‑14 there; they belong in a separate method also in your utility class:-The advantage of clone() and the Arrays#copyXXX() methods is that they are ready‑made methods and you don't have to write your own code, which might introduce errors.
Why did you call your local variable flag? Almost any boolean can be used as a flag, so that name adds nothing to the clarity of the code.
But you don't really have two sorting techniques at all. What algorithm are you using? You are doing the same thing in both. Find out about different sorting algorithms; for an int[], you will probably find quicksort (Tony Hoare) gives the fastest performance.
Why are you sorting backwards?
This Java™ Tutorials link isn't directly relevant to int[]s, but it is still worth reading.
 
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. You showed ONE method of sorting an array. Both snippets of code use the same Bubble Sort algorithm.

2. The two snippets show different implementations for copying the array that contains the data to sort. Copying and sorting are two different operations.

3. The name flag is not very descriptive. The name swapped describes the purpose of that variable better.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:1. You showed ONE method of sorting an array. Both snippets of code use the same Bubble Sort algorithm.

2. The two snippets show different implementations for copying the array that contains the data to sort. Copying and sorting are two different operations.



from method 1 Line 4


from method 2 Line 3


I guess I should have been more explicit in my question...sorry. It seems to me that both of these lines of code do the same thing. I would like to know if one is preferred over the other. And if they do not do the same thing then I would like to know their differences.

3. The name flag is not very descriptive. The name swapped describes the purpose of that variable better.


I like the "swapped" descriptor. Thanks. I just didn't know what to call it so I called it flag, because that is what it is.  I realize that to most of you that this is pretty simple but to me, it seems like my code above is an interstate with a million cars racing. There is so much going on, and I only have 4 methods and 59 lines of code. But, the more I write the code out, the more I repeat the steps it becomes a little clearer and I can sort of see a road map. Not quite there but it is definitely more visible since the first day I began back in March.  
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lines 2-5 in the first snippet do the equivalent of line 3 in the second snippet. Line 4 of the first snippet only copies one element from the original array.

I try to make my code express intent more hence prefer the second way you showed. Lines 2-5 of the first snippet is more about implementation. It's the difference between looking at the steering wheel of a car (method 2) versus a cut-away section drawing of the rack-and-pinion system. The steering wheel is the intent, the detailed drawing shows the implementation.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Both those methods have the advantage that you are copying the original array, rather than Arrays#sort() which has the array sent rather like an output parameter; you are changing the state of the array passed as an argument. I would prefer to use the clone() method to copy the array.



I have read about cloning and it seemed to me that copy and clone worked the same with regard to an int and clone would be better used in a non primitive data type situation. Did I misunderstand this?



I wouldn't have lines 11‑14 there; they belong in a separate method also in your utility class:



Is this because I have a copy and a sort in the same methods?






The advantage of clone() and the Arrays#copyXXX() methods is that they are ready‑made methods and you don't have to write your own code, which might introduce errors.



I am trying to get better at the whole logic mindset. I do realize that there are better and more efficient ways but I am trying to get better at the thinking part of it at the moment. In your opinion, as a beginner am I wasting my time with trying to do the work 100% myself
or should I choose to use the prebuilt methods and code first. I feel like I need to be able to write the code that does the work, that way one day when I am coding a project for real, and/or reading other people's code I will have a better understanding of the code that has been written.
What is your opinion on this?

Why did you call your local variable flag? Almost any boolean can be used as a flag, so that name adds nothing to the clarity of the code.


Because I did not know what to call it so I called it what is is and that is a flag. But, thanks to Junilu , I will forever call it "swapped". I have to laugh at this because I can't believe I didn't know what to call it and it just makes sense
to call it swapped. Btw what would you call it?



Find out about different sorting algorithms; for an int[], you will probably find quicksort (Tony Hoare) gives the fastest performance.



Thank you. I have bookmarked quicksort and will be reviewing this.


[quick]Why are you sorting backwards?
This Java™ Tutorials link isn't directly relevant to int[]s, but it is still worth reading.

No specific reason for sorting backwards. I could have used ascending. Just practicing.  Thanks for the tutorial, and always a big thanks for your feedback.

 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Lines 2-5 in the first snippet do the equivalent of line 3 in the second snippet. Line 4 of the first snippet only copies one element from the original array.

I try to make my code express intent more hence prefer the second way you showed. Lines 2-5 of the first snippet is more about implementation. It's the difference between looking at the steering wheel of a car (method 2) versus a cut-away section drawing of the rack-and-pinion system. The steering wheel is the intent, the detailed drawing shows the implementation.



Thank you for the clarification. I now see your point and should have included lines 2-5. My question is as a beginner should I be so concerned about implementation...how it works. The 2nd snippet I feel robs me at this time  as a beginner of understanding how the code actually "can" perform the work. What I am concerned about is that I will get to a fork in the road of my learning and if I only use the most efficient methods of performing a task like snippet 2 without knowing how it actually does the work like in snippet 1, then I may actually be robbing myself of part of the learning process.  What is your opinion on this?
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:as a beginner am I wasting my time with trying to do the work 100% myself or should I choose to use the prebuilt methods and code first


It's good to go through the implementation of an algorithm yourself a few times until you understand the logic and the implementation. After that, your focus really is on the intent (you may notice I tend to use this word a lot). Good programs express intent and hide implementation.

I did not know what to call it so I called it what is is and that is a flag. ... I have to laugh at this because I can't believe I didn't know what to call it and it just makes sense to call it swapped.


This is very common especially with beginners and programmers who are focused on the implementation. Look at the other names you use: sortIntegerArray (you misspelled "Integer" by the way). The "integer array" part is totally about the implementation and it's redundant given the parameter declaration. Here's basically the same code with a stronger focus on expressing intent:

Line 8 is per Campbell's suggestion to move the implementation of the "swap" intent to a method of its own.  The names express the role/intent/purpose of each thing rather than the implementation.
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:[My question is as a beginner should I be so concerned about implementation...how it works. The 2nd snippet I feel robs me at this time  as a beginner of understanding how the code actually "can" perform the work. What I am concerned about is that I will get to a fork in the road of my learning and if I only use the most efficient methods of performing a task like snippet 2 without knowing how it actually does the work like in snippet 1, then I may actually be robbing myself of part of the learning process.  What is your opinion on this?


It depends on the kind of programming you're doing. If you're doing computer science-y work where you need to know the intricate details and need to squeeze every last bit of performance you can out of an algorithm, then sure, you need to know how things work.

However, when I'm solving real-world business problems, there are a lot of things I would rather not reinvent the wheel for if someone (or a bunch of someones) have already spent the time and effort figuring out the details of common but complicated operations.

If I'm solving business problems, I'd rather focus on the business domain concerns rather than say database concerns or networking concerns. That's why each platform, Java included, has so many different frameworks and libraries so that application programmers can focus on solving domain-specific problems which are hard enough as it is to solve without having to deal with the nitty-gritty details of networking, security, transaction processing, database, etc.

However, if you want to be a developer of frameworks and/or libraries, then it's useful to have a good grasp of how all the nitty-gritty stuff works.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote: It depends on the kind of programming you're doing. If you're doing computer science-y work where you need to know the intricate details and need to squeeze every last bit of performance you can out of an algorithm, then sure, you need to know how things work.

However, when I'm solving real-world business problems, there are a lot of things I would rather not reinvent the wheel for if someone (or a bunch of someones) have already spent the time and effort figuring out the details of common but complicated operations.

If I'm solving business problems, I'd rather focus on the business domain concerns rather than say database concerns or networking concerns. That's why each platform, Java included, has so many different frameworks and libraries so that application programmers can focus on solving domain-specific problems which are hard enough as it is to solve without having to deal with the nitty-gritty details of networking, security, transaction processing, database, etc.

However, if you want to be a developer of frameworks and/or libraries, then it's useful to have a good grasp of how all the nitty-gritty stuff works.



Thank you for your insight. At this moment I am not really sure where I am heading but what I do know is that I wish to learn have an understanding of Java.
 
Campbell Ritchie
Marshal
Posts: 69859
278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:. . . Did I misunderstand this? . . .

Maybe yes. If you use clone() on an array of primitives or immutable reference types, you have no problems caused by having two references to the same object.

Is this because I have a copy and a sort in the same methods? . . .

It is because you will do the same task again, in which case you will be repeating your code.

I am trying to get better at the whole logic mindset. . . .

Good point. It is probably a good idea for beginners to write their own algorithms, but you will find it much easier to use ready‑made code when you are more experienced.

. . . But, thanks to Junilu , I will forever call it "swapped". . . .

Much better name; thank you, Junilu.

. . . . Just practicing.

Good idea. As long as you aren't deleting every file in sight or something equally daft, you can learn a lot by trying strange bits of code and seeing what happens.

Thanks . . . thanks . . .

That's a pleasure
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Learning the syntax of a language is important at a fundamental level but it's not what I would advise focusing on. It should take you a few weeks to a couple of months to become familiar with syntax and control structures. Then it's on to bigger things like learning idioms (common ways to express ideas), learning patterns (common ways to organize solutions), and learning problem solving techniques.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Junilu and Campbell, thank you both again.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Line 8 is per Campbell's suggestion to move the implementation of the "swap" intent to a method of its own.  The names express the role/intent/purpose of each thing rather than the implementation.



I created a method in which I perform the swap, then called it from the sortArray. It is not working, and hanging up and I can enter integer after integer.  Can you point me in the direction as to where I am incorrect?
I can see in my IntelliJ debug mode that I see that I return the updated swap array the first time,  but once back in the sortArray it is back to the original unswapped array. I can't seem to figure out how to get out of this and retain the updated swap array once back in the sortArray method.
I can tell I'm close.



       
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why create a clone of the array in swap? That makes the method swap elements in the cloned array. Also, there's no need to return anything from the method. The JavaDocs would be something like this:

What you're looking for is basically a "side-effect" of calling the swap() method - the array you pass to it will be mutated as a result of the swap operation.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Why create a clone of the array in swap? That makes the method swap elements in the cloned array. Also, there's no need to return anything from the method. The JavaDocs would be something like this:

What you're looking for is basically a "side-effect" of calling the swap() method - the array you pass to it will be mutated as a result of the swap operation.



I was thinking I have to return the swapped array so that it can be printed to the console either by passing it to the printSortedArray method directly or with a println directly in the printSortedArray after calling this in the main method.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please forgive me for posting the entire code again but i am really confused. I commented out the array.clone() in the swap method and it works perfectly. Why did that prevent the code from working?
Also, I returned it (even though it is never used according to IntelliJ) from the swap method but I did not return it anywhere and the sortedArray method can see it because when I call the sortArray method in my main method the array returned is in sorted and swapped order. How is this??





 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

What you're looking for is basically a "side-effect" of calling the swap() method - the array you pass to it will be mutated as a result of the swap operation.



So what you are stating is that I am actually updating (mutating the sortValuesArray[] when I pass it to the swap() method and perform the operations on the array[],
which is in reality the sortValuesArray[] that is located in the sortArray() method,
which I return to the main() method, then pass it to the printSortedArray() method.

If I am correct, then if I copy an array[], and pass it off to another method, then update that array[], now the original array[] has been changed too, which may not be what I want, but
in this case it is.

If this is the case, this is pretty cool and almost like a revelation. One of those moments where you realize "I understand this."

 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It sounds like you're understanding it correctly although your description is a bit convoluted. An array is an object so when you pass a reference to an array to a method, anything you do the array through the array parameter is done to the same array referenced by the sortValuesArray. Both reference the same array object.

As I mentioned before, a name like sortValuesArray is not a very good name because of the word "Array" in the name: it leaks an implementation detail. You don't want to do that. You normally want to avoid leaking information about the implementation. Try to stick with names that express intent instead. The name sortedNumbers is fine although I think it's still redundant because the type declaration of int[] already informs the reader that it's an array of numbers.
 
Campbell Ritchie
Marshal
Posts: 69859
278
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:. . . . The JavaDocs would be something like this:

Can I enhance that documentation comment please.The bits about current implementation and two indices the same are there mostly so you can see whether they do or don't appear in different sections of the generated HTML. It is often a bad idea to show implementation details in documentation comments. The bits about range constitute part of the contract for that method; “You must pass the right indices, otherwise I won't work, but shall throw an exception.” The awkward line breaks should disappear from the generated document.
I envisage this method being a member of a utility class, so the method would be marked public static. The javadoc tool usually omits private class members and constructors from its output. I have omitted any mention of what happens if you pass null, sers should know it won't be a pretty sight.

What you're looking for is basically a "side-effect" . . . the array you pass to it will be mutated . . .

That is the same as what I said a few days ago about changing the state of the argument object. In this case I would be happy to use the side‑effect.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell and Junilu, I did not realize why the swap() method would be void and that I could pass the array as a parameter to the swap method and then change it, and the original array would be changed too, but I now understand a little more after learning the difference about reference types and value types.  Thank you both very much.
 
Campbell Ritchie
Marshal
Posts: 69859
278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure and I am sure Junilu would say the same.

bryant rob wrote:. . . pass the array as a parameter to the swap method and then change it, and the original array would be changed too . . .

That depends on how many arrays you have references to, and how many of those are copies of each other. If they are copies, you might have to change both. My idea about copies was that you retain the original array unchanged, just in case you want information about the original order.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, I do not wish to continue to beat this topic into the dirt but I have another questions. I think this would be an implementation question, so please correct me if I am wrong...I am trying to get the terminology right.

Since I am only wanting a certain piece of code to be executed (to swap my values around) if a given condition is true (if sortedIntArray[i] < sortedIntArray[i+1]), and I want to continue this until that condition is false , I am using a flag to set this condition to begin the while loop.

As a programmer, how will I know, "hey, I think I am going to need to set a flag for this piece of code because...........? I am looking for the reason behind the because.  In other words, how will I know I need to use a flag, and not think some other method will work better? I also realize that I could have used a do while loop,

but I am more interested in the flag concept here.  Lastly, is there some other method besides setting a flag that would work just as well?  



bryant rob wrote:

 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're implementing the Bubble Sort algorithm which calls for a flag to indicate whether or not a swap occurred. So, it's not really a matter of how you will know when to use a flag or not because whoever came up with the algorithm already decided that's what you should do.

Now, if you're coming up with a different algorithm, you may or may not employ a similar mechanism to determine whether or not to continue the sorting process. It all depends on what kind of process you think up, really. In general, a flag or semaphore is a commonly used design element to signal that something should be done.

The question you ask is kind of like asking how did the inventor of the rack-and-pinion steering system decide to use a rack and pinion instead of a recirculating ball? Or why did the inventor/designer of flip phone decide to make it a flip phone? Basically, it's just a product of someone's imagination and creativity to decide to do it one way or another. It almost seems like you're looking for some kind of formula or rule of thumb where, unfortunately (or fortunately, depending on your perspective), there isn't one.

There are other mechanisms or strategies you can use to perform sorting. Recursion is one of them. Divide-and-conquer is another. These are not necessarily mutually exclusive options either. You can use recursion and divide-and-conquer. Again, it just depends on what kind of process you can think up.
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's one thing you can improve in your program. Try to limit the scope of things to be as small as possible. In your code, you declare the temp variable in a scope that is wider than its actual use. This is poor form. You can delete line 3 and change line 8 to this:

And again, the name sortedIntArray is a poor choice of name because it mentions implementation details ("int" and "array"), information which already clearly shown in the declaration of that variable.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Here's one thing you can improve in your program. Try to limit the scope of things to be as small as possible. In your code, you declare the temp variable in a scope that is wider than its actual use. This is poor form. You can delete line 3 and change line 8 to this:

And again, the name sortedIntArray is a poor choice of name because it mentions implementation details ("int" and "array"), information which already clearly shown in the declaration of that variable.



Just so you know, I have since changed my code to remove the "Int" and "Array" from my variable and names, and will forever try to remember to leave those types of names for implementation, and it does save on typing as well.

Ok, so what you are saying the algorithms dictate the methods upon which we as programmers will perform certain functions. If I am going to use the Bubble sort algorithm then I know from the beginning that I will be needing to include a flag in the code to indicate a swap. Thanks for this.

The problem that I was having was I kept wondering where the "else" statement was, and when I did not use it for this situation, that somehow the flag was being used instead of the "else" and then I got to thinking how in the world will I ever be able to memorize this,  but I realize that is not the case.

Thank you for that clarification.  

As far as the temp variable, why do you think that the instructor did not initialize temp the way you did?

 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:
As far as the temp variable, why do you think that the instructor did not initialize temp the way you did?


Pessimistic/cynical answer: he/she didn't know better. My guess is that this is a carry-over practice from other languages where it's idiomatic to declare variables at one go before they're used. We did this in Pascal. COBOL is also like this, as well as old-style BASIC. In Java and other modern languages, you want to minimize the scope of variables so that access to them is clear and easy to analyze. The more you limit the scope of variables, the fewer potential problems (i.e. bugs) you'll have because of them.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:The more you limit the scope of variables, the fewer potential problems (i.e. bugs) you'll have because of them.



I was thinking when you stated to limit the scope of variables that this could lead to a bugging issue if the variable was erroneously initialized to some unwanted data type. You confirmed it. Thanks.
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:this could lead to a bugging issue if the variable was erroneously initialized to some unwanted data type. You confirmed it.


Since variables are strongly-typed in Java, there's really not much of a danger that it would be initialized to some unwanted data type. Its type will be whatever it's declared to be. The problem is access. The more widely accessible a variable is, the less control and predictability you have over the value that it will contain. This is why using global variables is discouraged since they have the widest accessibility and it's more difficult to pin down who is going to access it and when it's going to change. Global variables tend to make your code more tightly coupled and more difficult to test.
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume that, like most people, you only use your toothbrush in the bathroom so naturally, that's where you keep it, right? What would be the point of keeping a toothbrush in the bedroom?

Likewise, why make the temp variable accessible within the entire method when you're only using it once in the if-statement? Declaring the temp variable in the method scope instead of in the scope of the if-statement where it's used is like keeping your toothbrush in the bedroom instead of in the bathroom.
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:I got to thinking how in the world will I ever be able to memorize this


How does a basketball/football player know when to zig instead of zag? It comes with experience and developing a "feel" for what needs to be done. "Gut feel" or "intuition" is really just our brains subconsciously digging deep into experience and making very quick decisions about how we should react. As you keep writing code and getting feedback about what are good and not so good ways to organize your code, you'll start to develop that innate sense of what best to do in a certain situation. A key part of this learning is knowing principles and how to apply them. Principles like "keep your code loosely coupled and highly cohesive" and "keep it simple" and "keep it testable". Principles are the "good angels" of coding that keep you on the straight and narrow path. If you don't know them or ignore them, you'll soon find yourself quite literally in programmer hell.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:
Since variables are strongly-typed in Java, there's really not much of a danger that it would be initialized to some unwanted data type. Its type will be whatever it's declared to be. The problem is access. The more widely accessible a variable is, the less control and predictability you have over the value that it will contain. This is why using global variables is discouraged since they have the widest accessibility and it's more difficult to pin down who is going to access it and when it's going to change. Global variables tend to make your code more tightly coupled and more difficult to test.



I have enclosed my upated code for my sort() method and swap() method. One thing that I did was when I called the swap() from inside the sort() method I passed array to it as a parameter. I then used IntelliJ to debug and realized what I had done then changed it. I have to assume that this is a common error among beginners.

One last question, how can i save my swap() method and call it from any class or method  from any package in the future? Because it seems to me if I ever need a descending sort using the bubble sort algorithm then this is it.  Would this be a utility class?

 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you have a for-loop in swap()? That method is meant to do only one swap: switch the first and the second elements.

Coming back to names again, array is probably not the best name (I know, I suggested it, too. That only shows even experienced people need to be wary as well). I'd probably change that to something like numbers or data. As for indexStart and indexEnd, once you eliminate the for-loop, those won't make sense anymore. I would change those to something like first and second or even just i and j although I'd probably go with the former.
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:how can i save my swap() method and call it from any class or method  from any package in the future?


Since you declared swap() to be public static then you already have access to it globally. You just need to include an import or static import of whatever class this method is in.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Why do you have a for-loop in swap()? That method is meant to do only one swap: switch the first and the second elements.



Based upon your question, I should not have the for() in the swap() so I removed it...and it works. I'm guessing since I passed an array that has already been initialized in a previous method there is no need to initialize it again in the swap(). Thank you for that lesson.


This is what I have now for my swap() method and works like a charm. Thank you again, and thank you for having the patience.

 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

bryant rob wrote:how can i save my swap() method and call it from any class or method  from any package in the future?


Since you declared swap() to be public static then you already have access to it globally. You just need to include an import or static import of whatever class this method is in.



Would you recommend me creating a project in IntelliJ and possibly naming it "Utilities" and placing these types of methods in a class name that is fitting?
 
Junilu Lacar
Sheriff
Posts: 15808
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

bryant rob wrote:Would you recommend me creating a project in IntelliJ and possibly naming it "Utilities" and placing these types of methods in a class name that is fitting?


The project can be anything you want. What's important is the package name and the class name that you assign.

That being said, I've worked in Java since 2000 and have not found any need to create any utility libraries like that for any of the projects I've worked on. That's because there are already many libraries out there that have implemented this functionality and each project can differ as to the specific libraries they use for utilities. For me, methods like sort() and swap() are things I don't bother with since other people have already spent time and effort bothering with it for me.

Even if it's just for your personal projects, these are still way too low-level in my opinion. If you want, keep them around for sentimental reasons so that one day you can look back and reminisce about that time you were learning about sorting and swapping.
 
bryant rob
Ranch Foreman
Posts: 95
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

bryant rob wrote: methods like sort() and swap() are things I don't bother with since other people have already spent time and effort bothering with it for me.



If I was in need of a method like my sort and swap, where would i find a library that has implemented this functionality so that I could just call it instead of having to create this work again?  

I am assuming what you are talking about would be calling a method from a library similar to the date and time library?


 
Do not threaten THIS beaver! Not even with this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic