Categories
Programming & Web Development

Basic programming algorithm: Bubble Sort

Bubble sort is one of the most basic sorting algorithms in taught in computer science classes. It will order values in a list from smallest to largest passing several times through the list comparing two items at a time and reordering them. This algorithm is not very efficient with large lists because it has to evaluate every member of the list several times. The longer the list, the more it will take the algorithm to finish. In big-O notation, this algorithm’s efficiency is represented by: O(n2)

An explanation of bubble sort from Wikipedia:

Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

bubble sort example

While passing through the list, compare two elements, if the second one is bigger than the first, swap their positions in the list. Continue going through the list, comparing the next elements in the same way. Go through the list until no more swaps take place.

Pseudocode:

while not sorted:
  sorted = True
  for iterator = 1 to length_of_list - 1 do:
    check if pair is out of order:
    if list[iterator] is bigger than list[iterator+1] then
    swap them:
      temporal_value = list[iterator]
      list[iterator] = list[iterator+1]
      list[iterator+1] = temporal_value
      sorted = False
      skip to next element in list

PHP code example:

/**
 * Sort an array using bubble sort algorithm
 * @param array $list The list to be sorted
 * @return array The sorted array
 */
function bubbleSort($list) {
   while(!$sorted){
     $sorted = True;
     foreach($list as $key => $value) {
        if($list[$key] > $list[$key+1]) {
          $temp = $list[$key+1];
          $list[$key+1] = $list[$key];
          $list[$key] = $temp;
          $sorted = False;
        }
     }
   }
   return $list;
}

Python code example:

function bubbleSort(a_list):
  """ Sort an array using bubble sort algorithm """
  sorted = False
  length = len(a_list)
  while not sorted:
     sorted = True
     for position in range(length):
       if a_list[position] > a_list[position+1]:
         # Swap values
         a_list[position], a_list[position+1] = a_list[position+1], a_list[position]
         sorted = False
  return a_list

There is another way to write the bubble sort, by shrinking the list by one element after every pass. If you see the animated graphic above, after each pass, the last number is already in its correct place, so you don’t have to iterate over those every subsequent time. You can discard the last element each time, making the algorithm faster.

An example of this version in Python code would look like this:

function betterBubbleSort(a_list):
  """ Sort an array using bubble sort algorithm """
  length = len(a_list)
  while length:
     for position in range(length):
       if a_list[position] > a_list[position+1]:
         # Swap values
         a_list[position], a_list[position+1] = a_list[position+1],a_list[position]
     length -= 1
  return a_list

Do you have other ways of writing the bubble sort? Share them in the comments section below.

Categories
personal

Learn better by sharing your knowledge

Reading Sacha Chua’s blog post on testing what you know by sharing inspired me on how to practice some basic computer science skills I have not used much in a while but are very useful to have freshly in mind. I’ve been wanting to improve my computer algorithm knowledge skills for a while, but never got around to it, putting the task aside for “other important things”.

For a very basic start, an algorithm is a series of steps to accomplish something. A cooking recipe can be an algorithm for the dish, and like every recipe, there are several ways to make the same dish.

See, that wasn’t hard to explain at all! I hope the rest comes as easy as this one.

By sharing what I learn here in my blog, I will need to comprehend fully the concepts to write them down and I will also be practicing my programming skills, keeping a log of my notes for future reference and sharing with other people interested in the topic. Hopefully I will get comments with better ways to explain this concepts or better code examples. So this looks like a win-win situation for everyone.

By the way, if you want to read a fun blog with a mixture of cooking recipes (or algorithms) and politics, check out Tacos and Politics.

Categories
Photography

Instagram: A use for missed shots and crappy photos

There are many times in a photoshoot that you miss the shot. The image is out of focus, you get under or over exposed images, etc. Well, don’t throw them away, you can still use those shots.

Long leg jeans

I went to one of the Intermoda Trends runway and found out there was a new rule: No DSLR photography allowed. Why do this at a fashion show? I have no idea, but if you didn’t have a press pass, you could not use a DSLR. I was raging because I could see several people using mirrorless cameras with the same sensors as a DSLR shooting away, and just because my camera was “professional-looking” I could not use it and they could use theirs.

So I tried shooting “from the hip”, very discretely just aiming and trying to get a shot of the runway. I didn’t focus manually, since I had no chance to even check the viewfinder once. I relied on the autofocus for the first shots, then locked the focus and continued shooting. When I downloaded all my images for review, I found out, unsurprisingly, that I had 200 shots of unfocused models at the runway. The autofocus got locked focusing the front row, not the runway.

Long black dress

I thought of deleting them all, but for some reason just kept them as JPEGs. Then I remembered how Instagram has a very crappy quality, and immediately thought that it was the perfect place to put missed shots. I tested my theory and I got a lot of likes from those missed shots.

So if you have some out of focus images or crappy quality shots, don’t throw them away, try posting them on Instagram, as quality and sharpness is not one of its attributes.

Categories
personal

Replaced my Galaxy Nexus with a Motorola X

When I woke up in the morning, it never crossed my mind that I was going to change my phone that day.

I’ve been off contract for several months. If I wanted to go back in to contract, I would need a good deal since I was on an unlimited data plan that are no longer offered. Another benefit that I should look into a new contract is the price of a new phone.

Since I’ve used my Galaxy Nexus for two years and have been very happy with the stock Android experience, I didn’t want to go back into a custom branded phone; like something with Samsung’s Touchwiz for example.

I started the day by getting lunch at P.F. Chang’s, and right across the street there was a Telcel customer service office. So I went over there just to be curious on what was available, and surprisingly got a good deal: a lower rate contract since I not using all the minutes I was paying for, and a relatively good price on the Motorola X phone.

Samsung Galaxy Nexus vs Motorola X

Coming from using the Galaxy Nexus, the improvements are very noticeable. Not in the software, which are minor tweaks, but in the performance. The GNex has 1GB RAM vs the Moto X’s 2GB RAM that make a world of difference in load and response times.

The screen is very bright and I love the contrast (is it called dynamic range?) of the blacks and the bright colors.

Although the general software is pure Google Android, it has some special software like Touchless control and display notifications. I comes with Android 4.2.2, and not the current 4.3 version. The Motorola sales guy told me that it will upgrade to 4.4 “as soon as it comes out”, but I take his word with a grain of salt. You can also install the Motorola Connect Chrome extension so you can read your SMS messages and review your call log on the computer screen.

Also the camera software is different from stock Android, which I still haven’t tested thoroughly. Upgrading my mobile camera from the GNex’s 8 megapixel camera to the Moto X’s 10.2 megapixel camera sounds like a nice improvement that I still have to test and compare in detail. I like the fact that with two swings of the wrist the camera quickly activates. I got tired of spending 8 to 12 seconds to bring up the camera on the GNex, most times missing the moment, and don’t get me started on the focusing. The Moto X camera seems to focus pretty fast the couple times I’ve tried it so far.

The only complain I have so far on the Moto X is the Gallery app. It doesn’t sync all my web albums. So all I see are the photos stored in the phone. I don’t want to replace the gallery app with some untrusted version. The same thing happens with my CyanogenMod tablet, but I’m willing to experiment on that one more than on my new device.

I know that at the time of this writing and my recent purchase, the Nexus 5 is only days away from being announced. But I don’t regret my purchase. It will take weeks for it to start hitting the streets and months for it to get offered by my mobile provider at probably double the price than in the US. I guess I’ll still want a Nexus 5 when it comes out, but for now I can wait a few months, to save up for it while I figure out how I can order it from the US and get it shipped to Mexico, but more importantly, read comments and feedback from the early adopters.

Categories
Photography

Vogue Fashion Night Out 2013 Guadalajara

A few weeks ago the Vogue Fashion Night Out event took place in Guadalajara at the Andares shopping center. The shopping center is one of the most beautiful ones in the country, architecturally speaking, and this event was perfect for the place. Almost every store had DJs playing and gave free drinks and promotions. There was photo booths everywhere and the people assisting there looked great everyone wearing their best clothes. You couldn’t distinguish between models or shoppers, it was stunning.

Unfortunately it was a weekday, so I could only attend after day job hours, so I only saw the last runway. It featured two main styles: a very rock/punk style and an old fashion kind of 40’s look.

This was a challenging night for me, as my kit zoom lens is at the Nikon service repair shop. I only had my 50mm 1.8G lens, and with my D7000 DX body, it makes it almost an 85mm lens. Shooting with that in a very crowded place with fast moving models in the runway was a big challenge.

I managed to pull some few good shots that I’d like to share here.

Photographer with gold umbrella Shiny purple short dress Worried model girl Runway male model close-up portrait Purple and brown Black and silver accessories Black leather jeans and boots Black mini skirt in the runway Patterned stalkings Retro look Vest and hat Retro hairstyle with loops Veronica Assis and husband at the runway Retro style with a hat Keyboard rock player GST_0156

Categories
Photography

Tampico beach, I miss my hometown

Browsing in my photo collection from last year, I found these photos I had forgotten to process from RAW files.

Looking at them made me miss my hometown and its beach. It’s never been a highly touristic beach, although it does have its high season during spring break where thousands gather and there is no space to even stand. But it is a nice beach, most of the year is very calm with very few people around.

I have countless great memories here, as I grew up here and most of my teenage days I spent them at the beach, either alone or with friends, but I love being at the sea. It’s been a little more than 6 years that I’ve been living away from the sea and I still miss it every sunny day.

Mexican candy salesman at the beach

Traditional mexican sweets

At the beach there’s always people selling all kinds of stuff. These are the most traditional things you’ll find people sell at the beach: sweets, coconuts and corn.

A man proud of his work

Carrito de elotes y troles asados

Cold coconuts at the beach

Two seagulls chatting

Two guys with brazilian swimsuits catching some sun

Too many seagulls

San Bernardo at the beach

Seagull flight

Small seagull in the air

Whenever I see a bright sunny day, I always say “this is a great day to go to the beach”. A phrase commonly and easily said in my hometown. I guess old habits never die.