am_dot_com

SW 2022-04-27

Apr 27th, 2022 (edited)
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Arrays em JS (1)</title>
  6. <script src="definicoes.js"></script>
  7. </head>
  8. <body>
  9. <section>
  10. <h1>Arrays em JS</h1>
  11. <h2>Aspetos teóricos - formas de inserir</h2>
  12. </section>
  13. <hr>
  14. <script>
  15. var a1 = [1, 2, 3]
  16. //alias aliases pointer pointers reference references
  17. var a2 = a1 //a2 --> [1, 2, 3] <-- a1
  18. a2.push(999)
  19. document.write("a2: ", a2+"<br>")
  20. document.write("a1: ", a1+"<br>")
  21.  
  22. var n1=999, n2=333;
  23. /*
  24. will not work for value swapping
  25. because the params will work on copies of the originals
  26. NOT on the originals themselves
  27. This technique of argument-param association is called
  28. "pass by-value"
  29. The alternative is "pass by-reference" (not available in JS)
  30. */
  31. function swap (pN1, pN2){
  32. var temp = pN1
  33. pN1=pN2
  34. pN2=temp
  35. }
  36.  
  37. /*
  38. um array é, afinal, o endereço do primeiro dos seus elementos
  39. com acesso a esse endereço, é possível modificar o array
  40. é isso que o bubbleSort fez
  41. isto não contradiz que tenha acontecido pass-by-value
  42. */
  43. function bubbleSort(pCol){
  44. var bOrdenada=bTrocas=false
  45.  
  46. while(!bOrdenada){
  47. bTrocas = false
  48. //passeio do 1º ao penúltimo elemento
  49. for(
  50. var pos=0, penultima=pCol.length-1-1;
  51. pos<=penultima;
  52. pos+=1
  53. ){
  54. if(pCol[pos]>pCol[pos+1]){
  55. var temp=pCol[pos]
  56. pCol[pos]=pCol[pos+1]
  57. pCol[pos+1]=temp
  58. bTrocas=true
  59. }
  60. }
  61. //perguntar-nos "fiz trocas?"
  62. if (!bTrocas) bOrdenada=true
  63. }//while
  64. }//bubbleSort
  65.  
  66. /*
  67. "frase" double-quotes
  68. 'frase' single-quotes
  69. `frase` backticks
  70. */
  71. document.write(`Before swap n1=${n1} n2=${n2}<br>`)
  72. swap(n1, n2)
  73. document.write(`After swap n1=${n1} n2=${n2}<br>`)
  74.  
  75. document.write("<hr>")
  76.  
  77. var a2 = [3, 2, 1]
  78. document.write(`Before bubble sort: ${a2}<br>`)
  79. bubbleSort(a2)
  80. document.write(`After bubble sort: ${a2}<br>`)
  81.  
  82. </script>
  83. </body>
  84. </html>
Add Comment
Please, Sign In to add comment