Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Arrays em JS (1)</title>
- <script src="definicoes.js"></script>
- </head>
- <body>
- <section>
- <h1>Arrays em JS</h1>
- <h2>Aspetos teóricos - formas de inserir</h2>
- </section>
- <hr>
- <script>
- var a1 = [1, 2, 3]
- //alias aliases pointer pointers reference references
- var a2 = a1 //a2 --> [1, 2, 3] <-- a1
- a2.push(999)
- document.write("a2: ", a2+"<br>")
- document.write("a1: ", a1+"<br>")
- var n1=999, n2=333;
- /*
- will not work for value swapping
- because the params will work on copies of the originals
- NOT on the originals themselves
- This technique of argument-param association is called
- "pass by-value"
- The alternative is "pass by-reference" (not available in JS)
- */
- function swap (pN1, pN2){
- var temp = pN1
- pN1=pN2
- pN2=temp
- }
- /*
- um array é, afinal, o endereço do primeiro dos seus elementos
- com acesso a esse endereço, é possível modificar o array
- é isso que o bubbleSort fez
- isto não contradiz que tenha acontecido pass-by-value
- */
- function bubbleSort(pCol){
- var bOrdenada=bTrocas=false
- while(!bOrdenada){
- bTrocas = false
- //passeio do 1º ao penúltimo elemento
- for(
- var pos=0, penultima=pCol.length-1-1;
- pos<=penultima;
- pos+=1
- ){
- if(pCol[pos]>pCol[pos+1]){
- var temp=pCol[pos]
- pCol[pos]=pCol[pos+1]
- pCol[pos+1]=temp
- bTrocas=true
- }
- }
- //perguntar-nos "fiz trocas?"
- if (!bTrocas) bOrdenada=true
- }//while
- }//bubbleSort
- /*
- "frase" double-quotes
- 'frase' single-quotes
- `frase` backticks
- */
- document.write(`Before swap n1=${n1} n2=${n2}<br>`)
- swap(n1, n2)
- document.write(`After swap n1=${n1} n2=${n2}<br>`)
- document.write("<hr>")
- var a2 = [3, 2, 1]
- document.write(`Before bubble sort: ${a2}<br>`)
- bubbleSort(a2)
- document.write(`After bubble sort: ${a2}<br>`)
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment